TheAlgorithms/Python · error · ValueError

Incorrect input: Either {source_vertex} or {destination_vert

Error message

Incorrect input: Either {source_vertex} or {destination_vertex} does not exist

What it means

Raised by GraphAdjacencyMatrix.add_edge when source_vertex or destination_vertex is not in vertex_to_index (contains_vertex fails). The matrix implementation indexes cells by vertex position, so both endpoints must already be registered via add_vertex or the vertices constructor argument before any edge can reference them.

Source

Thrown at graphs/graph_adjacency_matrix.py:75

                msg = f"Invalid input: {edge} must have length 2."
                raise ValueError(msg)
            self.add_edge(edge[0], edge[1])

    def add_edge(self, source_vertex: T, destination_vertex: T) -> None:
        """
        Creates an edge from source vertex to destination vertex. If any
        given vertex doesn't exist or the edge already exists, a ValueError
        will be thrown.
        """
        if not (
            self.contains_vertex(source_vertex)
            and self.contains_vertex(destination_vertex)
        ):
            msg = (
                f"Incorrect input: Either {source_vertex} or "
                f"{destination_vertex} does not exist"
            )
            raise ValueError(msg)
        if self.contains_edge(source_vertex, destination_vertex):
            msg = (
                "Incorrect input: The edge already exists between "
                f"{source_vertex} and {destination_vertex}"
            )
            raise ValueError(msg)

        # Get the indices of the corresponding vertices and set their edge value to 1.
        u: int = self.vertex_to_index[source_vertex]
        v: int = self.vertex_to_index[destination_vertex]
        self.adj_matrix[u][v] = 1
        if not self.directed:
            self.adj_matrix[v][u] = 1

    def remove_edge(self, source_vertex: T, destination_vertex: T) -> None:
        """
        Removes the edge between the two vertices. If any given vertex
        doesn't exist or the edge does not exist, a ValueError will be thrown.

View on GitHub (pinned to f5988cc097)

Solutions

  1. Add both vertices first: `for v in (u, v): if not g.contains_vertex(v): g.add_vertex(v)` then add_edge.
  2. Ensure the vertices argument to the constructor covers every endpoint in edges.
  3. Validate edge endpoints against the vertex set during data loading.

Example fix

# before
graph.add_edge(new_node, existing_node)

# after
if not graph.contains_vertex(new_node):
    graph.add_vertex(new_node)
graph.add_edge(new_node, existing_node)
Defensive patterns

Strategy: validation

Validate before calling

for v in (source_vertex, destination_vertex):
    if not graph.contains_vertex(v):
        graph.add_vertex(v)
graph.add_edge(source_vertex, destination_vertex)

Type guard

def endpoints_present(graph, u, v) -> bool:
    return graph.contains_vertex(u) and graph.contains_vertex(v)

Prevention

When it happens

Trigger: Calling add_edge(u, v) before add_vertex(u) or add_vertex(v); building edges from data referencing nodes not in the vertices list passed to __init__; adding an edge after remove_vertex removed an endpoint.

Common situations: Edge lists from files/databases whose node ids are a superset of the declared vertex set; ordering bugs where edge insertion runs before vertex insertion; assuming add_edge auto-creates missing endpoints (it does not).

Related errors


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