TheAlgorithms/Python · error · ValueError

Invalid neighbor {neighbor_index} in node {node_index} adjac

Error message

Invalid neighbor {neighbor_index} in node {node_index} adjacency list.

What it means

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.

Source

Thrown at graphs/lanczos_eigenvectors.py:68

        raise ValueError("Graph should be a list of lists.")

    for node_index, neighbors in enumerate(graph):
        if not isinstance(neighbors, list):
            no_neighbors_message: str = (
                f"Node {node_index} should have a list of neighbors."
            )
            raise ValueError(no_neighbors_message)
        for neighbor_index in neighbors:
            if (
                not isinstance(neighbor_index, int)
                or neighbor_index < 0
                or neighbor_index >= len(graph)
            ):
                invalid_neighbor_message: str = (
                    f"Invalid neighbor {neighbor_index} in node {node_index} "
                    f"adjacency list."
                )
                raise ValueError(invalid_neighbor_message)


def lanczos_iteration(
    graph: list[list[int | None]], num_eigenvectors: int
) -> tuple[np.ndarray, np.ndarray]:
    """Constructs the tridiagonal matrix and orthonormal basis vectors using the
    Lanczos method.

    Args:
        graph: The graph represented as a list of adjacency lists.
        num_eigenvectors: The number of largest eigenvalues and eigenvectors
                          to approximate.

    Returns:
        A tuple containing:
            - tridiagonal_matrix: A (num_eigenvectors x num_eigenvectors) symmetric
                                  matrix.
            - orthonormal_basis: A (num_nodes x num_eigenvectors) matrix of orthonormal

View on GitHub (pinned to f5988cc097)

Solutions

  1. Remap ids to 0-based contiguous integers and ensure every neighbor index satisfies 0 <= idx < len(graph).
  2. Convert numpy floats to ints: `[[int(i) for i in row] for row in adj.tolist()]`.
  3. Strip sentinel values (-1, None) from neighbor lists before validation.
  4. Verify max index: `assert all(0 <= i < len(graph) for row in graph for i in row)`.

Example fix

# before
graph = [[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

# after (0-based)
graph = [[1, 2, 3], [0, 3], [0, 3], [0, 1, 2]]
Defensive patterns

Strategy: validation

Validate before calling

n = len(graph)
assert all(
    isinstance(i, int) and not isinstance(i, bool) and 0 <= i < n
    for row in graph
    for i in row
), "neighbor indices must be ints in [0, n)"

Type guard

def neighbors_in_range(graph) -> bool:
    n = len(graph)
    return all(0 <= i < n for row in graph for i in row if isinstance(i, int))

Prevention

When it happens

Trigger: 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'.

Common situations: 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.

Related errors


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