{"record":{"id":"58689ca46d9569d2","repo":"TheAlgorithms/Python","slug":"invalid-neighbor-neighbor-index-in-node-node-in","errorCode":null,"errorMessage":"Invalid neighbor {neighbor_index} in node {node_index} adjacency list.","messagePattern":"Invalid neighbor (.+?) in node (.+?) adjacency list\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/lanczos_eigenvectors.py","lineNumber":68,"sourceCode":"        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)\n\n\ndef lanczos_iteration(\n    graph: list[list[int | None]], num_eigenvectors: int\n) -> tuple[np.ndarray, np.ndarray]:\n    \"\"\"Constructs the tridiagonal matrix and orthonormal basis vectors using the\n    Lanczos method.\n\n    Args:\n        graph: The graph represented as a list of adjacency lists.\n        num_eigenvectors: The number of largest eigenvalues and eigenvectors\n                          to approximate.\n\n    Returns:\n        A tuple containing:\n            - tridiagonal_matrix: A (num_eigenvectors x num_eigenvectors) symmetric\n                                  matrix.\n            - orthonormal_basis: A (num_nodes x num_eigenvectors) matrix of orthonormal","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/lanczos_eigenvectors.py#L50-L86","documentation":"Raised by validate_adjacency_list in graphs/lanczos_eigenvectors.py when a neighbor entry inside a node's list is not an integer, is negative, or is >= len(graph) (out of range). Neighbors must be valid 0-based node indices into the same adjacency list. Note the isinstance check also rejects booleans-as-ints being used intentionally, and floats like 2.0 fail the strict int check.","triggerScenarios":"Passing neighbor ids that are 1-based (so max id == len(graph) triggers out-of-range); float indices like 2.0 from numpy conversion; string ids like '2'; negative sentinels such as -1 for 'no neighbor'.","commonSituations":"Graph data from formats with 1-based node numbering; numpy arrays converted with values becoming floats; external ids (strings, UUIDs) not remapped to dense 0-based indices; using -1 padding in fixed-width arrays.","solutions":["Remap ids to 0-based contiguous integers and ensure every neighbor index satisfies 0 <= idx < len(graph).","Convert numpy floats to ints: `[[int(i) for i in row] for row in adj.tolist()]`.","Strip sentinel values (-1, None) from neighbor lists before validation.","Verify max index: `assert all(0 <= i < len(graph) for row in graph for i in row)`."],"exampleFix":"# before\ngraph = [[2, 3], [1, 3], [1, 2], [0, 1, 2]]  # 1-based, node 3 out of range for len 4? no: 3 ok; but 1-based causes wrong graph\n\n# after (0-based)\ngraph = [[1, 2, 3], [0, 3], [0, 3], [0, 1, 2]]","handlingStrategy":"validation","validationCode":"n = len(graph)\nassert all(\n    isinstance(i, int) and not isinstance(i, bool) and 0 <= i < n\n    for row in graph\n    for i in row\n), \"neighbor indices must be ints in [0, n)\"","typeGuard":"def neighbors_in_range(graph) -> bool:\n    n = len(graph)\n    return all(0 <= i < n for row in graph for i in row if isinstance(i, int))","tryCatchPattern":null,"preventionTips":["Remap external ids to dense 0-based indices before calling.","After numpy conversion, cast rows to int: [[int(i) for i in row] for row in adj.tolist()].","Strip sentinel values (-1, None) used as padding in fixed-width inputs."],"tags":["graph","lanczos","index-validation","off-by-one"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}