{"record":{"id":"b0bda50ae1c69004","repo":"TheAlgorithms/Python","slug":"graph-should-be-a-list-of-lists","errorCode":null,"errorMessage":"Graph should be a list of lists.","messagePattern":"Graph should be a list of lists\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/lanczos_eigenvectors.py","lineNumber":50,"sourceCode":"def validate_adjacency_list(graph: list[list[int | None]]) -> None:\n    \"\"\"Validates the adjacency list format for the graph.\n\n    Args:\n        graph: A list of lists where each sublist contains the neighbors of a node.\n\n    Raises:\n        ValueError: If the graph is not a list of lists, or if any node has\n                    invalid neighbors (e.g., out-of-range or non-integer values).\n\n    >>> validate_adjacency_list([[1, 2], [0], [0, 1]])\n    >>> validate_adjacency_list([[]])  # No neighbors, valid case\n    >>> validate_adjacency_list([[1], [2], [-1]])  # Invalid neighbor\n    Traceback (most recent call last):\n        ...\n    ValueError: Invalid neighbor -1 in node 2 adjacency list.\n    \"\"\"\n    if not isinstance(graph, list):\n        raise ValueError(\"Graph should be a list of lists.\")\n\n    for node_index, neighbors in enumerate(graph):\n        if not isinstance(neighbors, list):\n            no_neighbors_message: str = (\n                f\"Node {node_index} should have a list of neighbors.\"\n            )\n            raise ValueError(no_neighbors_message)\n        for neighbor_index in neighbors:\n            if (\n                not isinstance(neighbor_index, int)\n                or neighbor_index < 0\n                or neighbor_index >= len(graph)\n            ):\n                invalid_neighbor_message: str = (\n                    f\"Invalid neighbor {neighbor_index} in node {node_index} \"\n                    f\"adjacency list.\"\n                )\n                raise ValueError(invalid_neighbor_message)","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/lanczos_eigenvectors.py#L32-L68","documentation":"Raised by validate_adjacency_list in graphs/lanczos_eigenvectors.py when the top-level `graph` argument is not a Python list. The Lanczos code expects the adjacency structure as a list of per-node neighbor lists (indices into the same list); anything else — a numpy array, dict, tuple, or generator — is rejected immediately with ValueError before per-node validation runs.","triggerScenarios":"Passing a numpy adjacency array (dense or not) directly; passing a dict {node: [neighbors]}; passing a tuple of lists; passing a generator/iterator of neighbor lists.","commonSituations":"Mixing numpy-based graph pipelines with this index-based list API; converting from an adjacency-matrix object and forgetting `.tolist()`; reusing a dict-based adjacency structure from another module (e.g. the johnson.py format).","solutions":["Convert before calling: `graph = np.asarray(adj).tolist()` for matrices, or `[v for _, v in sorted(adj_dict.items())]` for dicts.","Ensure the structure is literally `list[list[int]]` with nodes numbered 0..n-1.","Check `isinstance(graph, list)` in your own pipeline before invoking lanczos routines."],"exampleFix":"# before\nimport numpy as np\nadj = np.array([[0,1],[1,0]])\nT, Q = lanczos_iteration(adj, 2)  # raises\n\n# after\nT, Q = lanczos_iteration(adj.tolist(), 2)","handlingStrategy":"type-guard","validationCode":"import numpy as np\n\nif isinstance(graph, np.ndarray):\n    graph = graph.tolist()\nelif isinstance(graph, dict):\n    graph = [graph[i] for i in sorted(graph)]\nassert isinstance(graph, list)","typeGuard":"def is_adjacency_list(graph) -> bool:\n    return isinstance(graph, list) and all(isinstance(row, list) for row in graph)","tryCatchPattern":null,"preventionTips":["Keep one canonical graph format per pipeline and convert at the boundary.","numpy arrays: call .tolist() before passing to index-based list APIs.","Dict adjacency (node -> neighbors): convert to positional lists with a node-ordering."],"tags":["graph","lanczos","numpy","type-validation","adjacency-list"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}