{"record":{"id":"0ee27c025149d76a","repo":"TheAlgorithms/Python","slug":"incorrect-input-the-edge-already-exists-between-0ee27c","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":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/graph_adjacency_matrix.py","lineNumber":81,"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        # Get the indices of the corresponding vertices and set their edge value to 1.\n        u: int = self.vertex_to_index[source_vertex]\n        v: int = self.vertex_to_index[destination_vertex]\n        self.adj_matrix[u][v] = 1\n        if not self.directed:\n            self.adj_matrix[v][u] = 1\n\n    def remove_edge(self, source_vertex: T, destination_vertex: T) -> None:\n        \"\"\"\n        Removes the edge between the two vertices. If any given vertex\n        doesn't exist or the edge does not exist, a ValueError will be thrown.\n        \"\"\"\n        if not (\n            self.contains_vertex(source_vertex)\n            and self.contains_vertex(destination_vertex)\n        ):\n            msg = (","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/graph_adjacency_matrix.py#L63-L99","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Guard with `if not graph.contains_edge(u, v): graph.add_edge(u, v)`.","De-duplicate the edge list before insertion (for undirected graphs normalize each pair to a canonical order).","Catch ValueError when inserting best-effort edges from noisy data."],"exampleFix":"# before\nfor u, v in raw_edges:\n    graph.add_edge(u, v)  # raises on duplicates\n\n# after\nfor u, v in raw_edges:\n    if not graph.contains_edge(u, v):\n        graph.add_edge(u, v)","handlingStrategy":"validation","validationCode":"if not graph.contains_edge(source_vertex, destination_vertex):\n    graph.add_edge(source_vertex, destination_vertex)","typeGuard":"def can_add_edge(graph, u, v) -> bool:\n    if not (graph.contains_vertex(u) and graph.contains_vertex(v)):\n        return False\n    return not graph.contains_edge(u, v)","tryCatchPattern":"try:\n    graph.add_edge(u, v)\nexcept ValueError:\n    pass  # duplicate edge in simple graph; ignore","preventionTips":["De-duplicate edge lists before insertion; for undirected graphs canonicalize pair order.","Remember undirected edges are stored symmetrically — adding the reverse raises.","Use set-of-frozen-pairs bookkeeping when merging edge sources."],"tags":["graph","adjacency-matrix","duplicate-edge","simple-graph"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}