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
- 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.
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
- 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.
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
- Node {node_index} should have a list of neighbors.
- Vector length must match the number of nodes in the graph.
- Incorrect input: {vertex} does not exist in this graph.
- Incorrect input: The edge does NOT exist between {source_ver
- Incorrect input: Either {source_vertex} or {destination_vert
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/b0bda50ae1c69004.
Report an issue: GitHub.