TheAlgorithms/Python · error · ValueError

Vertex indexes must be in [0; size).

Error message

Vertex indexes must be in [0; size).

What it means

Raised by Graph.add_edge (graphs/breadth_first_search_zero_one_shortest_path.py:59) when to_vertex is negative or >= self.size (the vertex count fixed at construction). Vertices are integer indexes into a pre-allocated adjacency list, so destinations must fall in [0, size). Note the guard checks only to_vertex, not from_vertex — an out-of-range from_vertex will instead raise IndexError later.

Source

Thrown at graphs/breadth_first_search_zero_one_shortest_path.py:59

        >>> g.add_edge(1, 0, 1)
        >>> list(g[0])
        [Edge(destination_vertex=1, weight=0)]
        >>> list(g[1])
        [Edge(destination_vertex=0, weight=1)]
        >>> g.add_edge(0, 1, 2)
        Traceback (most recent call last):
            ...
        ValueError: Edge weight must be either 0 or 1.
        >>> g.add_edge(0, 2, 1)
        Traceback (most recent call last):
            ...
        ValueError: Vertex indexes must be in [0; size).
        """
        if weight not in (0, 1):
            raise ValueError("Edge weight must be either 0 or 1.")

        if to_vertex < 0 or to_vertex >= self.size:
            raise ValueError("Vertex indexes must be in [0; size).")

        self._graph[from_vertex].append(Edge(to_vertex, weight))

    def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
        """
        Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
              1                  1         1
         0--------->3        6--------7>------->8
         |          ^        ^        ^         |1
         |          |        |        |0        v
        0|          |0      1|        9-------->10
         |          |        |        ^    1
         v          |        |        |0
         1--------->2<-------4------->5
              0         1        1
        >>> g = AdjacencyList(11)
        >>> g.add_edge(0, 1, 0)
        >>> g.add_edge(0, 3, 1)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Fix the vertex count at construction: Graph(size=1 + max(all vertex ids))
  2. Convert 1-based IDs to 0-based: to_vertex = external_id - 1
  3. Bounds-check edges while loading: assert 0 <= to_vertex < g.size before add_edge

Example fix

# before
g = Graph(size=2)
g.add_edge(0, 2, 1)  # 2 out of range

# after
ids = [u for u, v, _ in edges] + [v for u, v, _ in edges]
g = Graph(size=1 + max(ids))
for u, v, w in edges:
    g.add_edge(u, v, w)
Defensive patterns

Strategy: validation

Validate before calling

if not (0 <= to_vertex < g.size and 0 <= from_vertex < g.size):
    raise IndexError(f"vertex out of range [0, {g.size})")
g.add_edge(from_vertex, to_vertex, weight)

Prevention

When it happens

Trigger: g.add_edge(0, 2, 1) on a Graph(size=2); negative indexes such as g.add_edge(0, -1, 1); off-by-one loops like `for v in range(size + 1)` producing v == size.

Common situations: Converting from 1-based external vertex IDs to 0-based indexes incorrectly; graphs built from files where an edge references a vertex ID >= declared vertex count; iterating inclusive ranges by mistake.

Related errors


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