TheAlgorithms/Python · error · ValueError

Invalid input: {edge} is the wrong length.

Error message

Invalid input: {edge} is the wrong length.

What it means

Raised by GraphAdjacencyList.__init__ (graphs/graph_adjacency_list.py:57) when any element of the edges parameter does not have exactly two elements. Edges must be 2-tuples/lists of (source, destination); this is an unweighted adjacency-list graph, so a weight in the edge would also trigger it.

Source

Thrown at graphs/graph_adjacency_list.py:57

        - edges: (list[list[T]]) The list of edges the client wants to
        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.adj_list: dict[T, list[T]] = {}  # dictionary of lists of T
        self.directed = directed

        # 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} is the wrong length."
                raise ValueError(msg)
            self.add_edge(edge[0], edge[1])

    def add_vertex(self, vertex: T) -> None:
        """
        Adds a vertex to the graph. If the given vertex already exists,
        a ValueError will be thrown.

        >>> g = GraphAdjacencyList(vertices=[], edges=[], directed=False)
        >>> g.add_vertex("A")
        >>> g.adj_list
        {'A': []}
        >>> g.add_vertex("A")
        Traceback (most recent call last):
        ...
        ValueError: Incorrect input: A is already in the graph.
        """
        if self.contains_vertex(vertex):
            msg = f"Incorrect input: {vertex} is already in the graph."

View on GitHub (pinned to f5988cc097)

Solutions

  1. Strip weights before constructing: edges = [(u, v) for u, v, *_ in raw_edges]
  2. Validate row lengths in your data loader and reject/repair malformed rows early
  3. Use a weighted graph class if you actually need edge weights

Example fix

# before
raw = [("A", "B", 5), ("B", "C", 2)]
g = GraphAdjacencyList(vertices=[], edges=raw)  # raises: wrong length

# after
raw = [("A", "B", 5), ("B", "C", 2)]
g = GraphAdjacencyList(vertices=[], edges=[(u, v) for u, v, _ in raw])
Defensive patterns

Strategy: validation

Validate before calling

normalized = []
for e in edges:
    if len(e) != 2:
        raise ValueError(f"edge must be (source, destination), got {e!r}")
    normalized.append((e[0], e[1]))
g = GraphAdjacencyList(vertices=vertices, edges=normalized)

Prevention

When it happens

Trigger: GraphAdjacencyList(edges=[('A','B','C')]) — three elements (e.g. a weighted edge); edges=[('A',)] — one element; edges=[['A','B','C']] from a loader that kept weights. Note the constructor iterates `edges or []`, so edges=0 or edges='' behave like no edges rather than raising.

Common situations: Feeding weighted edge lists (u, v, w) from other algorithms into this unweighted graph; heterogeneous data where some rows have extra columns; CSV rows loaded as tuples with trailing fields.

Related errors


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