Sub topic 9
Representation 3: the adjacency list
This chapter assumes you know Python lists, dictionaries, and sets, introductory Big-O, and the edge list and adjacency matrix from the earlier chapters. By the end you will build an adjacency list, read its costs, and avoid its common errors.
The idea
An adjacency list stores, for each vertex, the collection of its neighbors. In Python the usual form is a dictionary that maps each vertex to a list. Only edges that exist take space, so the structure fits sparse graphs well. A sparse graph has far fewer edges than the maximum possible.
Take the graph with edges A-B, A-C, B-D, and C-D.
Building one from an edge list
from collections import defaultdict
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u) # undirected: record both directions
print(graph["A"]) # ['B', 'C']
print(graph["D"]) # ['B', 'C']An undirected edge appears twice, once in each endpoint's list. For a directed edge u -> v, you would append only graph[u].append(v).
The result is:
| Vertex | Neighbors |
|---|---|
| A | B, C |
| B | A, D |
| C | A, D |
| D | B, C |
Costs
Let V be the number of vertices and E the number of edges.
| Operation | Cost with list neighbors |
|---|---|
| Space | O(V + E) |
| Iterate the neighbors of v | O(deg(v)) |
| Check whether edge u-v exists | O(deg(u)) |
| Add an edge | O(1) |
| Remove an edge | O(deg(u)) |
Iterating neighbors is the strength. Cost is proportional to the neighbors that exist, not to V. The weakness is edge lookup, which scans a list. If you need fast lookup, store neighbors in a set instead:
graph_sets = {
"A": {"B", "C"},
"B": {"A", "D"},
"C": {"A", "D"},
"D": {"B", "C"},
}
print("B" in graph_sets["A"]) # True, average O(1)
print("D" in graph_sets["A"]) # FalseSets give average constant-time lookup and removal. They lose neighbor order and cannot hold parallel edges.
Common errors
- Forgetting the reverse edge. In an undirected graph, adding only
graph[u].append(v)makesvunreachable from theuside of any traversal that starts atv. - Missing vertices. A vertex with no edges never appears as a key when you build from an edge list. Code that reads
graph[node]on a plaindictthen raisesKeyError. Add every vertex up front, or usedefaultdict. - Accidentally growing a
defaultdict. Readinggraph["Z"]on adefaultdictcreates an empty entry for"Z". Usegraph.get("Z", [])or"Z" in graphwhen you only want to check. - Counting edges twice. In an undirected graph, the sum of all list lengths is 2E, not E.
When to choose it
Pick an adjacency list when the graph is sparse and your algorithm walks the neighbors of each vertex, as breadth-first search does. Prefer a matrix when the graph is dense or you check arbitrary edges constantly. The trade-offs chapter compares all three structures side by side.
Exercise
Given the adjacency list {"A": ["B"], "B": ["C"], "C": []} for a directed graph, how many edges does it have, and what does the sum of the list lengths equal for an undirected graph with the same total edge count?
Show answer
The directed graph has 2 edges (A->B and B->C), which equals the sum of list lengths. For an undirected graph with E edges, each edge is stored twice, so the sum of list lengths is 2E.
Exercise
Write code that builds a directed adjacency list from the edges [("A", "B"), ("A", "C"), ("C", "B")] and prints the neighbors of "B". What does it print, and why?
Show answer
Use graph = defaultdict(list) and graph[u].append(v) for each edge. Printing graph["B"] gives [], because B has incoming edges but no outgoing edges, and a directed adjacency list stores only outgoing edges.