{"record":{"id":"e338424b64c74db3","repo":"TheAlgorithms/Python","slug":"invalid-input-edge-must-have-length-2","errorCode":null,"errorMessage":"Invalid input: {edge} must have length 2.","messagePattern":"Invalid input: (.+?) must have length 2\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/graph_adjacency_matrix.py","lineNumber":58,"sourceCode":"        pass in. Each edge is a 2-element list. Default is empty.\n        - directed: (bool) Indicates if graph is directed or undirected.\n        Default is True.\n        \"\"\"\n        self.directed = directed\n        self.vertex_to_index: dict[T, int] = {}\n        self.adj_matrix: list[list[int]] = []\n\n        # Falsey checks\n        edges = edges or []\n        vertices = vertices or []\n\n        for vertex in vertices:\n            self.add_vertex(vertex)\n\n        for edge in edges:\n            if len(edge) != 2:\n                msg = f\"Invalid input: {edge} must have length 2.\"\n                raise ValueError(msg)\n            self.add_edge(edge[0], edge[1])\n\n    def add_edge(self, source_vertex: T, destination_vertex: T) -> None:\n        \"\"\"\n        Creates an edge from source vertex to destination vertex. If any\n        given vertex doesn't exist or the edge already exists, a ValueError\n        will be thrown.\n        \"\"\"\n        if not (\n            self.contains_vertex(source_vertex)\n            and self.contains_vertex(destination_vertex)\n        ):\n            msg = (\n                f\"Incorrect input: Either {source_vertex} or \"\n                f\"{destination_vertex} does not exist\"\n            )\n            raise ValueError(msg)\n        if self.contains_edge(source_vertex, destination_vertex):","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/graph_adjacency_matrix.py#L40-L76","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Convert each edge to a 2-element pair, dropping weights: [e[:2] for e in edges].","If weights are required, use a weighted graph implementation instead of this unweighted matrix class.","Validate edge shape before constructing: assert all(len(e) == 2 for e in edges)."],"exampleFix":"# before\nGraphAdjacencyMatrix(vertices=[0,1,2], edges=[[0, 1, 5], [1, 2, 3]])\n\n# after\nGraphAdjacencyMatrix(vertices=[0,1,2], edges=[[0, 1], [1, 2]])","handlingStrategy":"validation","validationCode":"edges = [tuple(e) for e in edges if len(e) == 2]\n# or normalize weighted triples:\nedges = [(e[0], e[1]) for e in edges]","typeGuard":"def is_valid_edge_list(edges) -> bool:\n    return all(len(e) == 2 for e in (edges or []))","tryCatchPattern":null,"preventionTips":["This class only supports unweighted edges — strip weights before constructing.","Validate edge shape at the data boundary, before graph construction.","Prefer 2-tuples (u, v) over lists to make the shape explicit."],"tags":["graph","adjacency-matrix","constructor","edge-format"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}