Storing a graph: adjacency lists vs matrices
A graph problem hands you nodes and connections, and the first decision is how to hold them in memory. There are two standard answers, and which one you pick decides how fast every later step is.
01 Nodes and edges
A graph is a set of nodes and a set of edges, each edge joining two nodes. Cities and roads, users and friendships, web pages and links. Number the nodes 0 to n - 1 and the input often arrives as a plain edge list: one pair per connection.
Five nodes and five edges: (0, 1), (0, 2), (1, 2), (1, 3), (3, 4). The edges have no direction, so 0 - 1 is the same as 1 - 0.
An edge list is fine for storing, but bad for asking. To find 1's neighbours you would scan every edge. So you turn it into one of two shapes.
02 The matrix: a yes or no for every pair
An adjacency matrix is an n × n grid. Cell [u][v] is 1 when u and v are joined and 0 when they are not. Every possible pair has a cell, whether the edge exists or not.
- node 1
- an edge from 1
- no edge, still stored
- an edge
- no edge
For an undirected graph the grid is symmetric: [1][3] and [3][1] are both 1. Most cells are 0, and they take as much room as the ones.
03 The list: each node's real neighbours
An adjacency list keeps, for each node, only the nodes it is actually joined to. In Python that is a list of lists (or a dict of lists when the nodes are names, not numbers).
- node 1
- 1's neighbours
Each undirected edge appears twice, once in each end's list, so the five edges make ten entries. Nothing is stored for pairs that are not joined.
04 Build both from an edge list
Both shapes are built in one pass over the edges. The only thing to remember is that an undirected edge goes in both directions.
Here is the list half of that loop, one edge per step. Each edge touches two lists, one at each end. The last step's output is print(adj) added to the end of graph.py, run on Python 3.14.
- edge being read
- edge stored
- its two ends
- list just appended to
adj = [[] for _ in range(n)] gives every node its own empty list, before any edge is read. Even a node with no edges gets an entry.
05 What each one costs
Write V for the number of nodes and E for the number of edges. The matrix pays for every possible pair; the list pays only for edges that exist.
| Operation | Matrix | List |
|---|---|---|
| Memory | O(V²) | O(V + E) |
| Is u joined to v? | O(1) | O(degree of u) |
| List u's neighbours | O(V) | O(degree of u) |
| Add an edge | O(1) | O(1) |
| Visit every edge | O(V²) | O(V + E) |
Most real graphs are sparse: each node has a few edges, not one to every other node. Take 10,000 users with 5 friends each.
0. Listing one user's friends reads 10,000 cells to find 5.The matrix wins when the graph is dense (most pairs are joined) or small, or when you mostly ask "are these two joined?". Store each node's neighbours in a set and the list answers that in O(1) on average too.
06 The two questions in code
Nearly every graph algorithm asks two things over and over: are these two joined, and who are this node's neighbours. The second one is the one that matters most, because searches like BFS and DFS ask it for every node.
# Is there an edge 1 - 4?matrix[1][4] == 1 # one cell: O(1)# Who are 1's neighbours?for v in range(n): # the whole row: O(V)if matrix[1][v]:print(v)
# Is there an edge 1 - 4?4 in adj[1] # scan 1's list: O(degree)# Who are 1's neighbours?for v in adj[1]: # only the real ones: O(degree)print(v)
Walking every node's neighbours costs O(V²) with a matrix and O(V + E) with a list. That is the usual running time you see quoted for BFS and DFS, and it assumes a list.
07 Direction, weights and node objects
The two shapes stretch to cover the other kinds of graph you will meet.
- Directed: store an edge
u → vonce, inu's list or in cell[u][v]only. The matrix is no longer symmetric. - Weighted: store
(neighbour, weight)pairs in the list, or the weight itself in the matrix cell, with a value such asmath.inffor "no edge" when0is a real weight. - Node objects: each node is an object holding references to its neighbours. This is an adjacency list where the list lives inside the node, and it is how Clone Graph gives you its input.
D has no outgoing edges, but it still needs an entry. C → B is stored only under C.
08 When it goes wrong
[[0] * n] * nEvery row is the same rowThis makes one list and repeats a reference to it n times. Set m[0][1] = 1 and every row changes. Use [[0] * n for _ in range(n)].adj[u].append(v)Adding only one directionFor an undirected graph you also need adj[v].append(u). Miss it and a search from v never finds u.defaultdict(list)Nodes with no edges disappearA dict built only from edges has no key for a node with no edges. Count components over range(n), not over the dict's keys, or isolated nodes go uncounted.edges = [[1, 2], [2, 3]]Labels that start at 1Many inputs number nodes 1 to n. Size the structures n + 1, or subtract 1 from every label, and do the same everywhere.[[0] * 100_000 for _ in ...]A matrix for a big sparse graph100,000 nodes means 10 billion cells. Check the size limit in the problem before you reach for a matrix.