{"record":{"id":"042c440e7c8d035d","repo":"TheAlgorithms/Python","slug":"incorrect-input-vertex-already-exists-in-this-g","errorCode":null,"errorMessage":"Incorrect input: {vertex} already exists in this graph.","messagePattern":"Incorrect input: (.+?) already exists in this graph\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/graph_adjacency_matrix.py","lineNumber":125,"sourceCode":"                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 0.\n        u: int = self.vertex_to_index[source_vertex]\n        v: int = self.vertex_to_index[destination_vertex]\n        self.adj_matrix[u][v] = 0\n        if not self.directed:\n            self.adj_matrix[v][u] = 0\n\n    def add_vertex(self, vertex: T) -> None:\n        \"\"\"\n        Adds a vertex to the graph. If the given vertex already exists,\n        a ValueError will be thrown.\n        \"\"\"\n        if self.contains_vertex(vertex):\n            msg = f\"Incorrect input: {vertex} already exists in this graph.\"\n            raise ValueError(msg)\n\n        # build column for vertex\n        for row in self.adj_matrix:\n            row.append(0)\n\n        # build row for vertex and update other data structures\n        self.adj_matrix.append([0] * (len(self.adj_matrix) + 1))\n        self.vertex_to_index[vertex] = len(self.adj_matrix) - 1\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)","sourceCodeStart":107,"sourceCodeEnd":143,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/graph_adjacency_matrix.py#L107-L143","documentation":"Raised by GraphAdjacencyMatrix.add_vertex when contains_vertex(vertex) is True, i.e. the vertex already has an index in vertex_to_index. Vertices act as unique keys; re-adding one would corrupt the index mapping and matrix dimensions, so the request is rejected. It commonly fires from the constructor's loop over the `vertices` argument when that list contains duplicates.","triggerScenarios":"Calling add_vertex on an existing vertex; passing a `vertices` list with duplicate entries to __init__; adding a vertex twice in a data-ingestion loop without de-duplication.","commonSituations":"Ingesting node lists from data with repeated ids; combining vertex sets from multiple sources without set operations; re-running initialization code over an existing graph object.","solutions":["Guard: `if not graph.contains_vertex(v): graph.add_vertex(v)`.","De-duplicate the vertices list before passing it to the constructor: `vertices = list(dict.fromkeys(vertices))`.","Use a set to track added vertices during ingestion."],"exampleFix":"# before\nGraphAdjacencyMatrix(vertices=[1, 2, 2, 3])  # duplicate 2\n\n# after\nGraphAdjacencyMatrix(vertices=list(dict.fromkeys([1, 2, 2, 3])))","handlingStrategy":"validation","validationCode":"vertices = list(dict.fromkeys(vertices))  # order-preserving de-dup\ng = GraphAdjacencyMatrix(vertices=vertices)","typeGuard":"def no_duplicates(vertices) -> bool:\n    return len(vertices) == len(set(vertices))","tryCatchPattern":null,"preventionTips":["De-duplicate vertex lists before constructor or add_vertex loops.","Track added vertices in a set during ingestion.","Never re-run initialization over an already-populated graph object."],"tags":["graph","adjacency-matrix","duplicate-vertex","constructor"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}