TheAlgorithms/Python · error · ValueError

Graph should be a list of lists.

Error message

Graph should be a list of lists.

What it means

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.

Source

Thrown at graphs/lanczos_eigenvectors.py:50

def validate_adjacency_list(graph: list[list[int | None]]) -> None:
    """Validates the adjacency list format for the graph.

    Args:
        graph: A list of lists where each sublist contains the neighbors of a node.

    Raises:
        ValueError: If the graph is not a list of lists, or if any node has
                    invalid neighbors (e.g., out-of-range or non-integer values).

    >>> validate_adjacency_list([[1, 2], [0], [0, 1]])
    >>> validate_adjacency_list([[]])  # No neighbors, valid case
    >>> validate_adjacency_list([[1], [2], [-1]])  # Invalid neighbor
    Traceback (most recent call last):
        ...
    ValueError: Invalid neighbor -1 in node 2 adjacency list.
    """
    if not isinstance(graph, list):
        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)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert before calling: `graph = np.asarray(adj).tolist()` for matrices, or `[v for _, v in sorted(adj_dict.items())]` for dicts.
  2. Ensure the structure is literally `list[list[int]]` with nodes numbered 0..n-1.
  3. Check `isinstance(graph, list)` in your own pipeline before invoking lanczos routines.

Example fix

# before
import numpy as np
adj = np.array([[0,1],[1,0]])
T, Q = lanczos_iteration(adj, 2)  # raises

# after
T, Q = lanczos_iteration(adj.tolist(), 2)
Defensive patterns

Strategy: type-guard

Validate before calling

import numpy as np

if isinstance(graph, np.ndarray):
    graph = graph.tolist()
elif isinstance(graph, dict):
    graph = [graph[i] for i in sorted(graph)]
assert isinstance(graph, list)

Type guard

def is_adjacency_list(graph) -> bool:
    return isinstance(graph, list) and all(isinstance(row, list) for row in graph)

Prevention

When it happens

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

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

Related errors


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