TheAlgorithms/Python · error · ValueError

Vector length must match the number of nodes in the graph.

Error message

Vector length must match the number of nodes in the graph.

What it means

Thrown by multiply_matrix_vector() in the Lanczos eigenvector computation. The graph is given as an adjacency list (list of neighbor lists), so len(graph) is the node count, and the vector passed in must have exactly that many entries (vector.shape[0] == num_nodes). Any mismatch between vector dimension and graph size aborts the matrix-vector product before it starts.

Source

Thrown at graphs/lanczos_eigenvectors.py:156

    Args:
        graph: The adjacency list of the graph.
        vector: A 1D numpy array representing the vector to multiply.

    Returns:
        A numpy array representing the product of the adjacency list and the vector.

    Raises:
        ValueError: If the vector's length does not match the number of nodes in the
                    graph.

    >>> multiply_matrix_vector([[1, 2], [0, 2], [0, 1]], np.array([1, 1, 1]))
    array([2., 2., 2.])
    >>> multiply_matrix_vector([[1, 2], [0, 2], [0, 1]], np.array([0, 1, 0]))
    array([1., 0., 1.])
    """
    num_nodes: int = len(graph)
    if vector.shape[0] != num_nodes:
        raise ValueError("Vector length must match the number of nodes in the graph.")

    result: np.ndarray = np.zeros(num_nodes)
    for node_index, neighbors in enumerate(graph):
        for neighbor_index in neighbors:
            result[node_index] += vector[neighbor_index]
    return result


def find_lanczos_eigenvectors(
    graph: list[list[int | None]], num_eigenvectors: int
) -> tuple[np.ndarray, np.ndarray]:
    """Computes the largest eigenvalues and their corresponding eigenvectors using the
    Lanczos method.

    Args:
        graph: The graph as a list of adjacency lists.
        num_eigenvectors: Number of largest eigenvalues and eigenvectors to compute.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Construct the vector with exactly len(graph) entries, e.g. np.ones(len(graph)) or the normalized all-ones start vector used by find_lanczos_eigenvectors.
  2. Rebuild the vector whenever the graph changes; do not cache vectors across graph modifications.
  3. Add an assert len(vector) == len(graph) before the call in your own code to fail with your own context.

Example fix

# before
vector = np.ones(len(graph[0]))  # wrong: neighbors of first node
multiply_matrix_vector(graph, vector)

# after
vector = np.full(len(graph), 1.0) / np.sqrt(len(graph))
multiply_matrix_vector(graph, vector)
Defensive patterns

Strategy: validation

Validate before calling

n = len(graph)
assert vector.shape[0] == n, f"vector has {vector.shape[0]} entries, graph has {n} nodes"

Type guard

def is_compatible(graph: list[list[int]], vector: np.ndarray) -> bool:
    return isinstance(vector, np.ndarray) and vector.ndim == 1 and vector.shape[0] == len(graph)

Try / catch

try:
    y = multiply_matrix_vector(graph, vector)
except ValueError as e:
    raise ValueError(f"graph/vector mismatch for graph of {len(graph)} nodes: {e}") from e

Prevention

When it happens

Trigger: Calling multiply_matrix_vector(graph, vector) where vector was built from a different graph or with a hardcoded size, e.g. passing np.array([1, 1]) with a 3-node graph [[1,2],[0,2],[0,1]]. Also happens when the start vector for Lanczos is created with len(graph[0]) or number-of-edges instead of number-of-nodes.

Common situations: Reusing an eigenvector/starting vector from a previous graph run, off-by-one when constructing the initial vector, or mixing a degree-array length with the node count after graph mutation (nodes added/removed between building the vector and calling the routine).

Related errors


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