TheAlgorithms/Python · error · ValueError

Invalid input: {edge} must have length 2.

Error message

Invalid input: {edge} must have length 2.

What it means

Raised by the GraphAdjacencyMatrix constructor while processing the `edges` argument: every edge entry must be a sequence of exactly two endpoints (source, destination). Any entry with len(edge) != 2 is rejected with ValueError before add_edge is attempted. Note the constructor also treats falsey edges (None, []) as an empty list, so `edges=None` is fine but malformed entries are not.

Source

Thrown at graphs/graph_adjacency_matrix.py:58

        pass in. Each edge is a 2-element list. Default is empty.
        - directed: (bool) Indicates if graph is directed or undirected.
        Default is True.
        """
        self.directed = directed
        self.vertex_to_index: dict[T, int] = {}
        self.adj_matrix: list[list[int]] = []

        # Falsey checks
        edges = edges or []
        vertices = vertices or []

        for vertex in vertices:
            self.add_vertex(vertex)

        for edge in edges:
            if len(edge) != 2:
                msg = f"Invalid input: {edge} must have length 2."
                raise ValueError(msg)
            self.add_edge(edge[0], edge[1])

    def add_edge(self, source_vertex: T, destination_vertex: T) -> None:
        """
        Creates an edge from source vertex to destination vertex. If any
        given vertex doesn't exist or the edge already exists, a ValueError
        will be thrown.
        """
        if not (
            self.contains_vertex(source_vertex)
            and self.contains_vertex(destination_vertex)
        ):
            msg = (
                f"Incorrect input: Either {source_vertex} or "
                f"{destination_vertex} does not exist"
            )
            raise ValueError(msg)
        if self.contains_edge(source_vertex, destination_vertex):

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert each edge to a 2-element pair, dropping weights: [e[:2] for e in edges].
  2. If weights are required, use a weighted graph implementation instead of this unweighted matrix class.
  3. Validate edge shape before constructing: assert all(len(e) == 2 for e in edges).

Example fix

# before
GraphAdjacencyMatrix(vertices=[0,1,2], edges=[[0, 1, 5], [1, 2, 3]])

# after
GraphAdjacencyMatrix(vertices=[0,1,2], edges=[[0, 1], [1, 2]])
Defensive patterns

Strategy: validation

Validate before calling

edges = [tuple(e) for e in edges if len(e) == 2]
# or normalize weighted triples:
edges = [(e[0], e[1]) for e in edges]

Type guard

def is_valid_edge_list(edges) -> bool:
    return all(len(e) == 2 for e in (edges or []))

Prevention

When it happens

Trigger: Passing edges as triples like [u, v, weight] (a weighted-edge format this class does not support); passing a single flat list of vertices ['A','B','C'] instead of pairs; passing tuples/strings of length != 2 such as 'AB' (len 2, passes) vs 'ABC' (len 3, raises).

Common situations: Porting code from a weighted-graph library that uses (u, v, w) triples; feeding unzipped or flat data straight from JSON; assuming the matrix graph accepts the same edge schema as an edge-list file with weights.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/e338424b64c74db3. Report an issue: GitHub.