Skip to content

Storing a graph: adjacency lists vs matrices

BasicsConcept

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.

The example graph used on this page
Graph · 5 nodes, 5 edges
0
1
2
3
4

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.

Row 1 lists 1's connections
Graph · 5 nodes, 5 edges
0
1
2
3
4
Adjacency matrix · 5 × 5
01234
001100
110110
211000
301001
400010
  • 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).

The same graph as lists
Graph · 5 nodes, 5 edges
0
1
2
3
4
Adjacency list · node → neighbours
0→1, 21→0, 2, 32→0, 13→1, 44→3
  • 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.

graph.py
n = 5
edges = [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)]
matrix = [[0] * n for _ in range(n)]
for u, v in edges:
matrix[u][v] = 1
matrix[v][u] = 1 # undirected: write both ways
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # undirected: both ends learn the edge
print(matrix[1])
print(adj[1])
Text
[1, 0, 1, 1, 0]
[0, 2, 3]

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.

Building the adjacency list, edge by edge
Step 1 of 6
Graph · edges read in list order
0
1
2
3
4
adj · node → neighbours
0→[]1→[]2→[]3→[]4→[]
  • 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.

0 of 5 edges read

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.

Matrix vs list, for V nodes and E edges
OperationMatrixList
MemoryO(V²)O(V + E)
Is u joined to v?O(1)O(degree of u)
List u's neighboursO(V)O(degree of u)
Add an edgeO(1)O(1)
Visit every edgeO(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.

Matrix100,000,000 cells10,000 × 10,000 cells, and all but 50,000 of them are 0. Listing one user's friends reads 10,000 cells to find 5.
List50,000 entries25,000 friendships, each stored twice. Listing one user's friends reads exactly 5 entries.

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.

Matrix
# 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)
List
# 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 → v once, in u'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 as math.inf for "no edge" when 0 is 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.
A directed, weighted graph and its list
Directed, weighted
4125
A
B
C
D
List of (neighbour, weight)
A→(B, 4), (C, 1)B→(D, 5)C→(B, 2)D→none

D has no outgoing edges, but it still needs an entry. C → B is stored only under C.

Python
class Node:
def __init__(self, val):
self.val = val
self.neighbors = [] # references to other Node objects
a, b = Node(1), Node(2)
a.neighbors.append(b)
b.neighbors.append(a)

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.

09 Check yourself

Question

A road map has 1,000 junctions, and each one meets about 4 roads. You will run BFS on it. Which storage fits better?

Question

grid = [[0] * 3] * 3, then grid[0][1] = 1. What is grid[2][1]?

Question

Number of Provinces gives you isConnected, an n × n matrix. What does it cost to find one city's neighbours?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?