Sub topic 7
Representation 1: the edge list
This chapter covers the simplest way to store a graph, the edge list. It assumes you know Python lists, tuples, and sets, and introductory Big-O notation. It also assumes you know what vertices, edges, direction, and weight mean from the earlier chapters.
What an edge list is
An edge list stores a graph as a plain collection of edges. Each edge is a pair of vertices, written (u, v). The graph's vertices are implied by the pairs that appear.
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
print(len(edges)) # 4 edges
print(("A", "B") in edges) # True, but this check scans the whole listThe graph has four edges, so len(edges) is 4. The membership test ("A", "B") in edges compares against items one by one until it finds a match or runs out. That is a linear scan, O(E) where E is the number of edges.
Direction and weight
The same structure covers directed and weighted graphs with small changes.
- Directed: treat each tuple as ordered, so
("A", "B")means A to B only. For an undirected graph, pick one convention. Either store each edge once and treat it as unordered, or store both directions. - Weighted: use triples
(u, v, w).
weighted_edges = [("A", "B", 4), ("A", "C", 1), ("C", "B", 2), ("B", "D", 2)]
total = sum(w for _, _, w in weighted_edges)
print(total) # 9Costs
Let V be the number of vertices and E the number of edges.
| Operation | Edge list cost |
|---|---|
| Space | O(E) |
| Add an edge | O(1) (append) |
| Is there an edge from u to v? | O(E) |
| List the neighbors of u | O(E) |
| Iterate over all edges | O(E) |
Space is the strength here. A graph with a million vertices and few edges takes memory proportional to the edges only. Edge lookup and neighbor listing are the weakness, because the list has no index by vertex. Finding the neighbors of "A" means checking every edge:
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
def neighbors(edges, node):
result = []
for u, v in edges:
if u == node:
result.append(v)
elif v == node:
result.append(u)
return result
print(neighbors(edges, "A")) # ['B', 'C']This function treats edges as undirected. It touches every edge on every call. An algorithm that asks for neighbors once per vertex, such as a traversal, then costs O(V × E) in total.
Common errors
- Isolated vertices disappear. A vertex with no edges never appears in any pair. If it matters, keep a separate vertex collection, for example
vertices = {"A", "B", "C", "D", "E"}. - Duplicate edges. A list allows
("A", "B")twice. That is a parallel edge, which may or may not be what you want. Use a set of tuples to reject duplicates. - Mixed conventions. In an undirected graph,
("A", "B")and("B", "A")are the same edge. If you store only one orientation, your lookup must check both. - Using it for repeated queries. If your code calls
in edgesorneighborsin a loop, convert to another representation first.
When to use it
Choose an edge list when the algorithm works on edges as a whole, not on one vertex's neighbors. Sorting edges by weight is the typical case, as in Kruskal's minimum spanning tree algorithm. It is also a convenient input format, since files and databases often store graphs as one edge per row. Converting from an edge list to an adjacency matrix or adjacency list takes a single pass, which later chapters show.
Exercise
A graph has 1,000 vertices and 2,000 undirected edges stored once each in a Python list of tuples. Roughly how many tuple comparisons does neighbors(edges, "A") make in the worst case, and why is this a problem if you call it for every vertex?
Show answer
It examines all 2,000 edges, since the list has no index by vertex. Calling it for all 1,000 vertices costs about 2,000,000 edge checks (V × E). An adjacency list would reach each vertex's neighbors directly, so the same work would total about V + E.
Exercise
You store an undirected graph as a list of tuples, adding only ("B", "A"). Why does ("A", "B") in edges return False, and how can you fix the lookup?
Show answer
Tuples are ordered, so ("A", "B") and ("B", "A") are different values. Fix it by checking both orders, (u, v) in edges or (v, u) in edges, or by storing each edge in a canonical order such as sorted vertex names.