TheAlgorithms/Python · error · ValueError

Incorrect input: The edge already exists between {source_ver

Error message

Incorrect input: The edge already exists between {source_vertex} and {destination_vertex}

What it means

Raised by GraphAdjacencyMatrix.add_edge when both vertices exist but the matrix cell for (source, destination) is already 1 (contains_edge returns True). The class models a simple unweighted graph, so duplicate edges are rejected instead of stored. In an undirected graph the mirror cell is also set, so adding B->A after A->B triggers this too.

Source

Thrown at graphs/graph_adjacency_matrix.py:81

        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.
        """
        if not (
            self.contains_vertex(source_vertex)
            and self.contains_vertex(destination_vertex)
        ):
            msg = (

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard with `if not graph.contains_edge(u, v): graph.add_edge(u, v)`.
  2. De-duplicate the edge list before insertion (for undirected graphs normalize each pair to a canonical order).
  3. Catch ValueError when inserting best-effort edges from noisy data.

Example fix

# before
for u, v in raw_edges:
    graph.add_edge(u, v)  # raises on duplicates

# after
for u, v in raw_edges:
    if not graph.contains_edge(u, v):
        graph.add_edge(u, v)
Defensive patterns

Strategy: validation

Validate before calling

if not graph.contains_edge(source_vertex, destination_vertex):
    graph.add_edge(source_vertex, destination_vertex)

Type guard

def can_add_edge(graph, u, v) -> bool:
    if not (graph.contains_vertex(u) and graph.contains_vertex(v)):
        return False
    return not graph.contains_edge(u, v)

Try / catch

try:
    graph.add_edge(u, v)
except ValueError:
    pass  # duplicate edge in simple graph; ignore

Prevention

When it happens

Trigger: Calling add_edge(u, v) twice; adding both directions of an edge on an undirected graph; ingesting an edge list that contains duplicates or both (u,v) and (v,u) for an undirected graph.

Common situations: Loading raw edge lists without de-duplicating; undirected data where each connection appears twice (both directions); retry logic that re-inserts an edge after a partially failed batch.

Related errors


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