Sub topic 8
Storing a graph as an adjacency list
This chapter assumes you can write Python with dictionaries, sets, and functions, and that you know simple big-O notation. You should also know what vertices and edges are, and how undirected, directed, and weighted graphs differ. Here the focus is on how to store them.
What an adjacency list is
An adjacency list stores, for each vertex, the collection of vertices it connects to. If the edge A–B exists, then B appears in A's list of neighbors. The whole graph is a mapping from each vertex to its neighbors.
In Python, the most direct form is a dictionary whose keys are vertices. Each value is a collection of neighbors. This chapter uses a dictionary of dictionaries: the inner dictionary maps each neighbor to the weight of the edge. One structure then covers all three graph types.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
undirected = {}
add_edge(undirected, "A", "B")
add_edge(undirected, "B", "C")
directed = {}
add_edge(directed, "A", "B", directed=True)
add_edge(directed, "B", "C", directed=True)
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(undirected) # {'A': {'B': 1}, 'B': {'A': 1, 'C': 1}, 'C': {'B': 1}}
print(directed) # {'A': {'B': 1}, 'B': {'C': 1}, 'C': {}}How the three graph types map onto it
The same function handles every case. Only two things change: whether the reverse entry is written, and what the inner value holds.
| Graph type | Entries written for edge u–v | Inner value |
|---|---|---|
| Undirected | `graph[u][v]` and `graph[v][u]` | Usually 1, or a placeholder |
| Directed | `graph[u][v]` only | Usually 1, or a placeholder |
| Weighted | One or both, depending on direction | The weight |
For an undirected graph, each edge appears twice. This is the most common source of bugs. If you add only one direction, the graph silently becomes directed, and traversals will miss vertices.
Why every vertex gets a key
Look at the second line of add_edge: graph.setdefault(v, {}). It creates an entry for the target vertex even when that vertex has no outgoing edges. In the directed example, C has an empty dictionary.
Without this line, a later graph["C"] raises KeyError. Any traversal that visits C and then looks up its neighbors would crash. Giving every vertex a key means that a missing key always signals a vertex that is not in the graph, not a vertex with no neighbors.
A vertex with no edges at all needs its own call, because add_edge only creates vertices that appear in an edge:
def add_vertex(graph, u):
graph.setdefault(u, {})
add_vertex(undirected, "Z")
print(undirected["Z"]) # {}Reading the structure
Three operations come up constantly, and each has a clear cost with this layout.
- Neighbors of u: iterate
graph[u]. The cost is proportional to the number of neighbors. - Is there an edge u to v: test
v in graph[u]. Dictionary lookup takes O(1) on average. - Weight of edge u to v: read
graph[u][v], also O(1) on average.
Because the inner collection is a dictionary, edge lookup is constant time. If you stored neighbors in a plain list instead, the same check would scan the list and cost O(degree of u). Many tutorials use lists of neighbors for simplicity. That is fine for traversal but slower for edge queries, and it has no place to hold a weight except tuples such as (v, weight).
Degree from an adjacency list
Out-degree is the size of a vertex's inner dictionary. In-degree is harder, because the structure is organized by source vertex.
def out_degree(graph, u):
return len(graph[u])
def in_degree(graph, u):
return sum(1 for v in graph if u in graph[v])
g = {}
add_edge(g, "A", "B", directed=True)
add_edge(g, "C", "B", directed=True)
print(out_degree(g, "A")) # 1
print(in_degree(g, "B")) # 2out_degree is O(1). in_degree checks every vertex, so it costs O(V), where V is the number of vertices. If your algorithm asks for in-degrees repeatedly, you have two options. You can compute all in-degrees in one pass over the edges, which costs O(V + E). Or you can maintain a second, reversed adjacency list that maps each vertex to the vertices pointing at it.
For an undirected graph, the two directions are identical, and len(graph[u]) is simply the degree.
Memory and time costs
Let V be the number of vertices and E the number of edges.
| Operation | Cost |
|---|---|
| Storage | O(V + E) |
| Iterate all neighbors of u | O(out-degree of u) |
| Edge test or weight lookup | O(1) average |
| Iterate all edges | O(V + E) |
| Out-degree of u | O(1) |
| In-degree of u | O(V) by scanning |
An undirected edge is stored twice, so it counts as two entries even though it is one edge. The storage bound is still O(V + E). The key point is that space grows with the edges that exist, not with every possible pair of vertices. For sparse graphs, where E is much smaller than V squared, this is a large saving. Road networks and social networks are typical examples.
Using the list in an algorithm
Traversal algorithms are designed around the neighbor loop for v in graph[u]. Breadth-first search shows this directly. It marks each vertex as seen when it is queued, so no vertex is processed twice.
from collections import deque
def bfs(graph, start):
seen = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
return order
print(bfs(undirected, "A")) # ['A', 'B', 'C']Each vertex is dequeued once, and each adjacency entry is examined once. That gives O(V + E) in total. The adjacency list is what makes this bound possible, because the loop touches only real neighbors and never tests absent pairs.
The weighted version of the loop uses graph[u].items() to get each neighbor and its weight together. Dijkstra's algorithm, covered later, relies on exactly that.
Common errors
- One-directional undirected edges. Writing only
graph[u][v]for an undirected graph. Always use the helper, or write both entries. - Missing keys for sink vertices. A vertex that only appears as a target has no key, so
graph[v]fails. Create the key when you add the edge. - Shared inner dictionaries. Building the graph with
dict.fromkeys(vertices, {})makes every vertex share one dictionary. Adding a neighbor to one adds it to all. Use{v: {} for v in vertices}instead. - Mutating while iterating. Adding or removing edges inside
for v in graph[u]raises aRuntimeErroror gives wrong results. Iterate overlist(graph[u])if you must change it. - Duplicate edges. Adding the same edge twice overwrites the weight rather than creating a parallel edge. If your problem needs parallel edges, this structure cannot represent them. You would store a list of weights per neighbor instead.
- Self-loops in undirected graphs. The edge A–A writes
graph["A"]["A"]twice to the same slot, so it is stored once. Whether that counts as one or two toward degree is a convention you should decide on.
Removing edges
Removal mirrors insertion. For an undirected graph, delete both entries.
def remove_edge(graph, u, v, directed=False):
graph[u].pop(v, None)
if not directed:
graph[v].pop(u, None)
remove_edge(undirected, "A", "B")
print(undirected["A"]) # {}Using pop(v, None) avoids a KeyError when the edge is already absent. Removing a vertex is more expensive in a directed graph, because you must scan every inner dictionary to delete edges that point to it. In an undirected graph you only need to visit its own neighbors.
Exercise
A teammate builds an undirected graph by calling graph.setdefault(u, {})[v] = 1 once per edge, with no reverse entry. They then run bfs(graph, "C") on the graph with edges A–B and B–C. What goes wrong, and what is the fix?
Show answer
The graph is stored as a directed graph with edges A to B and B to C, and C is not even guaranteed to have a key. BFS from C visits only C, because C has no outgoing entries, so A and B are never reached. The fix is to write the reverse entry as well, graph[v][u] = weight, and to create a key for every vertex. The add_edge helper with directed=False does both.
Exercise
A directed graph has 1,000 vertices and 5,000 edges. Roughly how many inner-dictionary entries does the adjacency list hold, and how would you find in-degrees for all vertices efficiently?
Show answer
It holds 5,000 entries, one per directed edge, plus 1,000 outer keys, so O(V + E). To get all in-degrees efficiently, make one pass over every edge and increment a counter for each target vertex. That costs O(V + E), instead of calling the O(V) in_degree function once per vertex, which costs O(V squared).