Sub topic 10
Adjacency list or matrix: choosing between them
What this chapter assumes
You should know how to build an adjacency list (a dictionary mapping each vertex to its neighbors) and an adjacency matrix (a square table where cell [i][j] describes the edge from vertex i to vertex j). You should also be comfortable with big-O notation, where V is the number of vertices and E is the number of edges.
Both structures can hold undirected, directed, and weighted graphs. This chapter compares what they cost and shows how to pick one.
The working model: density decides
A graph with V vertices has at most V × V possible directed edges. Undirected graphs have at most V(V − 1)/2 distinct edges, ignoring self-loops. The ratio of actual edges to possible edges is the graph's density.
- A sparse graph has E far below V². Road networks, social networks, and dependency graphs are sparse. Each vertex touches a handful of others, even when V is in the millions.
- A dense graph has E close to V². Examples are a table of pairwise distances between 200 cities, or a complete "who played whom" tournament.
The matrix always spends V² cells, no matter how few edges exist. The list spends space in proportion to V + E. Most of the choice follows from that difference.
Cost comparison
The table assumes the adjacency list is a dictionary of dictionaries, as in the earlier chapters. Lookups into the inner dictionary are O(1) on average. With a plain list of neighbors, an edge test would instead cost O(deg(u)), where deg(u) is the number of neighbors of u.
| Operation | Adjacency list (dict of dicts) | Adjacency matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Is there an edge u to v? | O(1) average | O(1) |
| Read the weight of u to v | O(1) average | O(1) |
| List the neighbors of u | O(deg(u)) | O(V) |
| Visit every edge | O(V + E) | O(V²) |
| Add or change an edge | O(1) average | O(1) |
| Remove an edge | O(1) average | O(1) |
| Add a vertex | O(1) | O(V) to append a row and a column |
| Out-degree of u | O(1) | O(V) |
| In-degree of u | O(V) by scanning every vertex | O(V) by scanning a column |
| Breadth-first search | O(V + E) | O(V²) |
Two rows decide most real choices:
- Listing neighbors. Almost every traversal algorithm, including breadth-first search and Dijkstra's algorithm, asks "what are the neighbors of u?" The list answers by touching only real neighbors. The matrix must scan a whole row of V cells, even if only two are filled.
- Space. A matrix for one million vertices needs 10¹² cells, which is far too large. A sparse list for the same graph might need only a few million entries.
A dictionary-based list already matches the matrix on edge tests. The matrix's advantage is therefore smaller in Python than in textbooks that describe lists of neighbors, and it applies mainly to dense graphs.
Building both from the same data
The following program converts a dictionary-of-dictionaries graph into a matrix. It also compares the two on a sparse path graph. Run all the blocks in this chapter in one file, because later blocks reuse the functions from this one.
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
def to_matrix(graph):
names = sorted(graph)
index = {name: i for i, name in enumerate(names)}
n = len(names)
matrix = [[None] * n for _ in range(n)]
for u in graph:
for v, w in graph[u].items():
matrix[index[u]][index[v]] = w
return names, index, matrix
def has_edge_list(graph, u, v):
return v in graph[u]
def has_edge_matrix(matrix, index, u, v):
return matrix[index[u]][index[v]] is not None
def neighbors_matrix(names, matrix, index, u):
return [names[j] for j, w in enumerate(matrix[index[u]]) if w is not None]
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
names, index, matrix = to_matrix(weighted)
print(names) # ['A', 'B', 'C']
print(matrix) # [[None, 4, 1], [4, None, 2], [1, 2, None]]
print(has_edge_list(weighted, "A", "B")) # True
print(has_edge_matrix(matrix, index, "A", "B")) # True
print(neighbors_matrix(names, matrix, index, "A")) # ['B', 'C']
n = 1000
path = {}
for i in range(n - 1):
add_edge(path, i, i + 1)
list_entries = sum(len(neighbors) for neighbors in path.values())
matrix_cells = n * n
print(list_entries) # 1998
print(matrix_cells) # 1000000The path graph has 999 undirected edges. Each edge is stored twice in the list, so the list holds 1,998 entries. The matrix holds 1,000,000 cells, and 998,002 of them are empty. Finding the neighbors of one vertex in this graph costs at most two steps in the list and a 1,000-cell scan in the matrix.
Where the matrix wins
The matrix is the better choice in these cases:
- The graph is dense. When most cells are filled, the matrix wastes little space. Its flat table also has less per-entry overhead than a dictionary entry, which stores a key, a value, and hash bookkeeping. The exact crossover density depends on your language and data types, so measure it if memory matters.
- You do constant-time edge tests in a tight loop. Array indexing is simple and predictable. The matrix needs no hashing.
- The algorithm works on all pairs. Algorithms that fill a V × V table of answers, such as all-pairs shortest paths, already pay V² space. A matrix input fits naturally.
- Vertices are already numbered 0 to V − 1. No index mapping is needed.
- You want to treat the graph as numbers. A matrix can be used with numerical libraries, for example to count walks by matrix multiplication.
The list is the better choice in these cases:
- The graph is sparse. This is the common case.
- You traverse the graph. Neighbor iteration is the core step of breadth-first search, depth-first search, and Dijkstra's algorithm.
- The vertex set changes. Adding a vertex to a list is one dictionary insertion. Adding one to a matrix means growing every row.
- Vertices have arbitrary labels. Strings, tuples, or objects work directly as dictionary keys.
Common errors
Using 0 as the "no edge" marker
A weight of 0 is a legal weight. If you fill an empty matrix with 0, you cannot tell "no edge" from "edge of weight 0". Use None or float("inf") for missing edges, and test with is not None, not with truthiness.
zero = {}
add_edge(zero, "X", "Y", 0)
_, idx, m = to_matrix(zero)
cell = m[idx["X"]][idx["Y"]]
print(cell) # 0
print(bool(cell)) # False, so a truthiness test wrongly says "no edge"
print(cell is not None) # TrueFor shortest-path work, float("inf") is often the better marker because adding to it still gives infinity. A distance matrix also usually puts 0 on the diagonal, because a vertex is zero distance from itself. That is a different meaning from "a self-loop of weight 0", so decide which one you are storing.
Forgetting that undirected means symmetric
In an undirected graph, matrix[i][j] and matrix[j][i] must always agree. If you update only one of them, the graph silently becomes directed. The add_edge function guards against this for the list by writing both directions, and any matrix update function should do the same. A symmetric matrix wastes about half its cells, though the cost does not change big-O.
Counting edges wrongly
An undirected edge appears twice in either structure. The sum of all inner dictionary sizes is 2E for an undirected graph, so divide by 2 to get E. A self-loop appears once in the list and once on the diagonal, so this rule breaks when self-loops exist. Count them separately if your data may contain them.
Scanning for in-degree
Out-degree is len(graph[u]). In-degree needs a scan of every vertex's neighbors, which costs O(V) with the dictionary-of-dictionaries shape and O(V + E) in a list of lists. If your algorithm asks for in-degree often, keep a second "reverse" adjacency list, or compute all in-degrees in one pass.
Parallel edges
Both the dictionary and the matrix hold one value per ordered pair. A second edge from A to B with a different weight overwrites the first. If your data has parallel edges, such as two flights on the same route, either keep the minimum weight when only the best matters, or store a list of weights per pair.
Treating labels as matrix indexes
A matrix is indexed by integers. If vertices are strings, you need an index map like the index dictionary above. Mixing up a label and its position causes wrong answers that raise no error. Keep the names list and the index dictionary together, and convert only at the edges of your program.
Rebuilding the matrix for every change
Converting a list to a matrix costs O(V²). Doing it inside a loop that adds edges makes the whole program quadratic or worse. Choose one representation for the mutable stage of your program, and convert once if another stage needs the other form.
A practical rule
Start with the dictionary-of-dictionaries adjacency list. It handles all three graph types, supports O(1) average edge tests, and makes traversal proportional to the real size of the graph. Switch to a matrix when you can show that the graph is dense, that V is small enough for V² cells, and that your main operations are edge lookups or all-pairs computation.
Exercise
A directed graph has 5,000 vertices and 40,000 edges. Estimate the number of cells in an adjacency matrix and the number of entries in an adjacency list, and say which representation you would use for breadth-first search.
Show answer
The matrix has 5,000 × 5,000 = 25,000,000 cells. The list has 5,000 vertex entries plus 40,000 edge entries, so about 45,000 items in total. The density is 40,000 / 25,000,000 = 0.16 percent, so the graph is very sparse. Use the adjacency list. Breadth-first search then costs O(V + E) = about 45,000 steps, while the matrix would cost O(V²) = 25,000,000 steps because each vertex scan reads a full row.
Exercise
You store a weighted graph as a matrix filled with 0 for "no edge". The graph contains a legitimate edge from X to Y with weight 0. What goes wrong, and how do you fix it?
Show answer
The edge looks identical to a missing edge, so a test such as if matrix[i][j]: treats the edge as absent, and any algorithm that skips zero cells ignores it. Fix it by filling empty cells with None (or float("inf") for distance calculations) and testing with is not None (or comparing against infinity).
Exercise
Your program calls in_degree on every vertex of a directed graph stored as a dictionary of dictionaries, using the scan from the earlier chapter. With V vertices and E edges, what is the total cost, and how can you reduce it?
Show answer
Each call scans all V vertices' neighbor dictionaries and tests membership, so one call is O(V) and V calls cost O(V²). Compute all in-degrees in a single pass instead. Create a counter for every vertex, then for each vertex u and each neighbor v in graph[u], add 1 to the counter for v. That costs O(V + E) in total.