{"record":{"id":"fb40095e104e3244","repo":"TheAlgorithms/Python","slug":"incorrect-input-the-edge-already-exists-between","errorCode":null,"errorMessage":"Incorrect input: The edge already exists between {source_vertex} and {destination_vertex}","messagePattern":"Incorrect input: The edge already exists between (.+?) and (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"warning","filePath":"graphs/graph_adjacency_list.py","lineNumber":99,"sourceCode":"        Creates an edge from source vertex to destination vertex. If any\n        given vertex doesn't exist or the edge already exists, a ValueError\n        will be thrown.\n        \"\"\"\n        if not (\n            self.contains_vertex(source_vertex)\n            and self.contains_vertex(destination_vertex)\n        ):\n            msg = (\n                f\"Incorrect input: Either {source_vertex} or \"\n                f\"{destination_vertex} does not exist\"\n            )\n            raise ValueError(msg)\n        if self.contains_edge(source_vertex, destination_vertex):\n            msg = (\n                \"Incorrect input: The edge already exists between \"\n                f\"{source_vertex} and {destination_vertex}\"\n            )\n            raise ValueError(msg)\n\n        # add the destination vertex to the list associated with the source vertex\n        # and vice versa if not directed\n        self.adj_list[source_vertex].append(destination_vertex)\n        if not self.directed:\n            self.adj_list[destination_vertex].append(source_vertex)\n\n    def remove_vertex(self, vertex: T) -> None:\n        \"\"\"\n        Removes the given vertex from the graph and deletes all incoming and\n        outgoing edges from the given vertex as well. If the given vertex\n        does not exist, a ValueError will be thrown.\n        \"\"\"\n        if not self.contains_vertex(vertex):\n            msg = f\"Incorrect input: {vertex} does not exist in this graph.\"\n            raise ValueError(msg)\n\n        if not self.directed:","sourceCodeStart":81,"sourceCodeEnd":117,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/graph_adjacency_list.py#L81-L117","documentation":"Raised by GraphAdjacencyList.add_edge (graphs/graph_adjacency_list.py:99) when an edge between source_vertex and destination_vertex already exists. This graph forbids parallel/multi-edges, so adding the same pair twice is rejected. In undirected mode (directed=False) the reverse direction also counts as the same edge via contains_edge.","triggerScenarios":"g.add_edge('A','B') twice; in undirected graphs, add_edge('A','B') then add_edge('B','A') raises because the first call appended B to A's list and A to B's list; loading an edge list that contains the same pair in both orders.","commonSituations":"Symmetric datasets (e.g. friendship graphs) that list each relationship twice; merging multiple edge files with overlapping pairs; loops that re-add edges on retry or re-ingestion.","solutions":["Guard with contains_edge: if not g.contains_edge(src, dst): g.add_edge(src, dst)","Deduplicate symmetric pairs when loading undirected graphs: edges = {frozenset((u, v)) for u, v in raw} (add explicit handling if self-loops are possible)","Catch ValueError where duplicates are expected and skip them"],"exampleFix":"# before\nfor u, v in raw_edges:\n    g.add_edge(u, v)  # raises on repeated/symmetric pairs\n\n# after\nfor u, v in raw_edges:\n    if not g.contains_edge(u, v):\n        g.add_edge(u, v)","handlingStrategy":"validation","validationCode":"if not g.contains_edge(source_vertex, destination_vertex):\n    g.add_edge(source_vertex, destination_vertex)","typeGuard":null,"tryCatchPattern":"try:\n    g.add_edge(src, dst)\nexcept ValueError as exc:\n    if \"already exists\" in str(exc):\n        pass  # skip duplicate\n    else:\n        raise","preventionTips":["Remember undirected graphs count (u,v) and (v,u) as the same edge","Deduplicate symmetric pairs with frozenset((u, v)) when loading undirected data"],"tags":["graphs","duplicate","edge","undirected"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}