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 GraphAdjacencyList.contains_edge when either endpoint is not a vertex of the graph. Unlike a pure predicate, this implementation validates inputs and throws ValueError instead of returning False for missing vertices. So a seemingly read-only query can raise if the graph does not contain the queried nodes.

Source

Thrown at graphs/graph_adjacency_list.py:179

        Returns True if the graph contains the vertex, False otherwise.
        """
        return vertex in self.adj_list

    def contains_edge(self, source_vertex: T, destination_vertex: T) -> bool:
        """
        Returns True if the graph contains the edge from the source_vertex to the
        destination_vertex, False otherwise. If any given vertex doesn't exist, 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} "
                f"or {destination_vertex} does not exist."
            )
            raise ValueError(msg)

        return destination_vertex in self.adj_list[source_vertex]

    def clear_graph(self) -> None:
        """
        Clears all vertices and edges.
        """
        self.adj_list = {}

    def __repr__(self) -> str:
        return pformat(self.adj_list)


class TestGraphAdjacencyList(unittest.TestCase):
    def __assert_graph_edge_exists_check(
        self,
        undirected_graph: GraphAdjacencyList,
        directed_graph: GraphAdjacencyList,

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard the query: `if graph.contains_vertex(u) and graph.contains_vertex(v) and graph.contains_edge(u, v)`.
  2. Filter candidate endpoints to the graph's vertex set before probing edges.
  3. Catch ValueError when scanning arbitrary pairs where missing vertices are expected.

Example fix

// before
if graph.contains_edge(u, v):  # raises if u or v absent
    ...

// after
if (
    graph.contains_vertex(u)
    and graph.contains_vertex(v)
    and graph.contains_edge(u, v)
):
    ...
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

try:
    has = graph.contains_edge(u, v)
except ValueError:
    has = False

Prevention

When it happens

Trigger: Calling contains_edge(u, v) where u or v was never added or was removed; probing many candidate edges against a graph built from a subset of nodes; calling contains_edge after clear_graph().

Common situations: Developers assuming contains_edge is total (never raises) and using it as a filter over arbitrary node pairs; validation code that checks edges before checking vertices; graph rebuilt from filtered data while edge candidates come from the unfiltered set.

Related errors


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