Kodewick
Start learning →
Storing a graph: adjacency matrix and list30 / 52

Storing a graph: adjacency matrix and list

Lesson 30 of 52 · Part 6 · Graphs · about 16 minutes

A graph is stored as an adjacency matrix, an n × n 2D list where checking one edge takes one step, or as an adjacency list, a defaultdict(list) that keeps only the edges that exist and suits sparse graphs.

A city has ten thousand junctions, each joined to about three roads. Before a navigation app can find a route, it has to get "what connects to what" into memory. The obvious way is a table of ten thousand rows by ten thousand columns, where row i, column j says whether a road runs from i to j: a hundred million cells. Each cell of a Python list is an 8-byte reference, so the references alone take 800 MB, and 99.97% of them are 0. Store instead, for each junction, only the few it really connects to: thirty thousand items in all, a megabyte or two. This lesson covers the two ways to store a graph and when to pick each. Every algorithm in the rest of this chapter (BFS, DFS, topological sort, Dijkstra, minimum spanning trees) starts with "how is the graph stored".

Vertices, edges and degree

A graph is made of vertices and the edges that join them. The number of vertices is n and the number of edges is e.

  • When edges have no direction, the graph is undirected: friendship, where A being B's friend means B is A's friend.
  • When edges have a direction, the graph is directed: following someone, one-way streets, course prerequisites, drawn as arrows.
  • When each edge carries a number (a distance, a cost, a time), the graph is weighted, and the number is the edge's weight.
  • The number of edges at a vertex is its degree. In a directed graph it splits in two: edges going out give the out-degree, edges coming in the in-degree.

An undirected graph with 5 vertices and 5 edges: every edge counts once at each end, so the degrees always add up to twice the number of edges

This lesson uses this graph throughout. In a program, a graph most often arrives as an edge list: edges = [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)], one tuple per edge. Both ways of storing it in this lesson are built from that list.

An undirected graph with n vertices has at most n(n − 1) / 2 edges. When it has few (e about the size of n) it is sparse: road networks, social networks and nearly every graph in a problem set are sparse. When it is close to the maximum, it is dense.

Choose one

An undirected graph has 7 edges. What do the degrees of all its vertices add up to?

Choose one

An undirected graph has 6 vertices (no repeated edges, no edge from a vertex to itself). What is the most edges it can have?

Adjacency matrix: an n × n table

Use an n × n 2D list matrix: if i and j are joined, matrix[i][j] = 1, otherwise 0. An undirected edge is written at both ends, so the matrix is symmetric about its diagonal.

01234001100110110211000301001400010
The adjacency matrix of this lesson's graph: row 1 holds three 1s, which is vertex 1's degree; "is there an edge between 1 and 3" is just matrix[1][3]
main.py
1n = 52edges = [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)]3 4matrix = [[0] * n for _ in range(n)]     # every row a new list5for u, v in edges:6    matrix[u][v] = 1                     # undirected: write both ends7    matrix[v][u] = 18 9for i in range(n):10    print(i, matrix[i], "degree =", sum(matrix[i]))11print("edge between 1 and 3:", matrix[1][3] == 1)12print("edge between 0 and 4:", matrix[0][4] == 1)13print("neighbours of 1:", [j for j in range(n) if matrix[1][j]])
Output
0 [0, 1, 1, 0, 0] degree = 2
1 [1, 0, 1, 1, 0] degree = 3
2 [1, 1, 0, 0, 0] degree = 2
3 [0, 1, 0, 0, 1] degree = 2
4 [0, 0, 0, 1, 0] degree = 1
edge between 1 and 3: True
edge between 0 and 4: False
neighbours of 1: [0, 2, 3]

Always build the matrix with [[0] * n for _ in range(n)]. Written as [[0] * n] * n, the n rows are one and the same list (the trap from chapter 0's "names and objects"): record one edge and every row changes.

A matrix answers "is there an edge between i and j" in one step: matrix[i][j], O(1). It has two drawbacks: it takes n² cells whether the edges exist or not, and finding all of i's neighbours means scanning all n cells of row i, even when i has only one neighbour.

Guess the outputA wrong guess is fine

A 3 × 3 matrix built with [[0] * 3] * 3, and only m[0][1] is changed. What does this print?

1m = [[0] * 3] * 32m[0][1] = 13print(m[2][1], m[0] is m[2])

Adjacency list: a list per vertex

An adjacency list stores only the edges that exist: each vertex gets a list of its neighbours. The handiest tool in Python is collections.defaultdict(list): the first time a vertex is used it gets an empty list by itself, so there is no need to check whether the key is there first.

01234

Edges added in the order 0–1, 0–2, 1–2, 1–3, 3–4: each edge is appended once at each end, so a list's order is the order the edges were added
main.py
1from collections import defaultdict2 3edges = [(0, 1), (0, 2), (1, 2), (1, 3), (3, 4)]4 5graph = defaultdict(list)6for u, v in edges:7    graph[u].append(v)                   # undirected: append once at each end8    graph[v].append(u)9 10for u in sorted(graph):11    print(u, graph[u])12print("neighbours of 1:", graph[1], "degree =", len(graph[1]))13print("edge between 1 and 3:", 3 in graph[1])14print("neighbours stored:", sum(len(a) for a in graph.values()))
Output
0 [1, 2]
1 [0, 2, 3]
2 [0, 1]
3 [1, 4]
4 [3]
neighbours of 1: [0, 2, 3] degree = 3
edge between 1 and 3: True
neighbours stored: 10

When the vertices are just the integers 0 to n − 1, a list of lists is common too: graph = [[] for _ in range(n)], used exactly the same way, graph[u].append(v). When the vertices are names (cities, courses, users), use a dict.

The order of the neighbours in a list is the order the edges were added. BFS and DFS later visit neighbours in that order: the same graph, with its edges added in another order, can be walked in another order. To check a visit order in a figure, read it against the lists.

Choose one

An undirected graph with 1000 vertices and 3000 edges is stored as a list of lists. How many items do all the lists hold together?

Exercise 1

Adjacency list from an edge list

Complete build(n, edges): the vertices are 0 to n − 1 and the edges are undirected. Return the adjacency list as a list of lists, neighbours in the order the edges were added. A vertex with no edges still gets an empty list.

It should print
[[1, 2], [0, 2, 3], [0, 1], [1], []]
[2, 3, 2, 1, 0]
exercise1.py
1def build(n, edges):2    graph = []3    # first an empty list for every vertex, then each edge at both ends4    return graph5 6g = build(5, [(0, 1), (0, 2), (1, 2), (1, 3)])7print(g)8print([len(a) for a in g])
Output
Press Run or Ctrl+Enter

Directed and weighted graphs

A directed graph records only one end: for u pointing to v, only graph[u].append(v). Then len(graph[u]) is u's out-degree; the in-degree has to be counted separately, as how many times u appears in all the lists.

main.py
1from collections import defaultdict, Counter2 3follows = [("Ann", "Bea"), ("Ann", "Cal"), ("Bea", "Cal"), ("Cal", "Ann")]4graph = defaultdict(list)5for u, v in follows:6    graph[u].append(v)                   # directed: only u -> v7 8indeg = Counter(v for u, v in follows)9for u in ["Ann", "Bea", "Cal"]:10    print(u, "follows", graph[u], "out-degree", len(graph[u]), "in-degree", indeg[u])
Output
Ann follows ['Bea', 'Cal'] out-degree 2 in-degree 1
Bea follows ['Cal'] out-degree 1 in-degree 1
Cal follows ['Ann'] out-degree 1 in-degree 2

In a weighted graph, each neighbour also carries a weight. The two usual ways to write it: tuples (neighbour, weight) in the lists, or a dict of dicts: graph[u][v] = w. The second one answers "what is the weight from u to v" in O(1), and works for directed and undirected graphs alike.

main.py
1from collections import defaultdict2 3roads = [("home", "school", 5), ("home", "shop", 2), ("shop", "school", 2), ("school", "library", 1)]4 5graph = defaultdict(dict)6for u, v, w in roads:7    graph[u][v] = w                      # undirected: write both ends8    graph[v][u] = w9 10print(graph["home"])11print("school to library:", graph["school"]["library"])12print("home joined directly to the library:", "library" in graph["home"])13for v, w in graph["school"].items():14    print("school ->", v, w)
Output
{'school': 5, 'shop': 2}
school to library: 1
home joined directly to the library: False
school -> home 5
school -> shop 2
school -> library 1

A matrix can hold weights too: put the weight in a cell with an edge and math.inf (no way through) in a cell without one.

Guess the outputA wrong guess is fine

The edge a–b is added twice, with different weights. What does this print?

1from collections import defaultdict2 3g = defaultdict(dict)4for u, v, w in [("a", "b", 3), ("b", "c", 1), ("a", "b", 5)]:5    g[u][v] = w6    g[v][u] = w7print(g["a"], len(g["b"]))
Choose one

In a directed graph's adjacency matrix, column 2 has three 1s. What does that tell you?

Exercise 2

Out-degree and in-degree

Complete degrees(edges): edges are directed (u, v), meaning u points to v. Return two dicts: each vertex's out-degree and in-degree (every vertex that appears in an edge counts, with 0 where there is nothing).

It should print
A out 2 in 0
B out 1 in 1
C out 1 in 2
D out 0 in 1
exercise2.py
1def degrees(edges):2    out_deg = {}3    in_deg = {}4    # first record every vertex that appears as 0, then count edge by edge5    return out_deg, in_deg6 7out_deg, in_deg = degrees([("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")])8for u in sorted(out_deg):9    print(u, "out", out_deg[u], "in", in_deg[u])
Output
Press Run or Ctrl+Enter

What each one costs

To find every neighbour of every vertex (which is what BFS and DFS do), how many looks does each way take? Count them on a sparse graph of 300 vertices and 600 edges:

main.py
1n = 3002edges = [(i, (i + 1) % n) for i in range(n)] + [(i, (i + 7) % n) for i in range(n)]3 4matrix = [[0] * n for _ in range(n)]5graph = [[] for _ in range(n)]6for u, v in edges:7    matrix[u][v] = matrix[v][u] = 18    graph[u].append(v)9    graph[v].append(u)10 11looks = 012found = 013for u in range(n):14    for v in range(n):                   # matrix: every row has n cells to look at15        looks += 116        if matrix[u][v]:17            found += 118print("adjacency matrix: looked at", looks, "cells, found", found, "neighbours")19 20looks = 021for u in range(n):22    for v in graph[u]:                   # adjacency list: only the real ones23        looks += 124print("adjacency list: looked at", looks)
Output
adjacency matrix: looked at 90000 cells, found 1200 neighbours
adjacency list: looked at 1200

The matrix looked at n² = 90,000 cells, 98.7% of them 0; the adjacency list looked at only 2e = 1,200 items. So walking a whole graph is O(n²) on a matrix and O(n + e) on adjacency lists.

Adjacency matrix matrix[u][v]Adjacency list, graph[u] a listDict of sets / dict of dicts
SpaceO(n²)O(n + e)O(n + e)
Edge between u and v?O(1)O(degree of u): v in list compares one by oneO(1) (on average)
All of u's neighboursO(n): scan a whole rowO(degree of u)O(degree of u)
Walk the whole graphO(n²)O(n + e)O(n + e)
Good fordense graphs, n of a few hundred, many "is there an edge" questionssparse graphs, nearly every problemsparse graphs with many "is there an edge" questions
Guess the outputA wrong guess is fine

Only the keys A and B were added, then the code asked about g["D"]. What does it print?

1from collections import defaultdict2 3g = defaultdict(list)4g["A"].append("B")5g["B"].append("C")6if g["D"]:7    print("D has neighbours")8print(len(g), sorted(g))

In interviews: the graph you are given is nearly always an edge list (edges, prerequisites) or a list of lists, and the first step is building the adjacency list yourself, O(n + e). Asked "matrix or list?": look at whether the graph is sparse or dense, then at which operation you need most, "is there an edge" or "all the neighbours".

Choose one

300 vertices with an edge between almost every pair, and the program keeps asking "what is the weight between i and j". Which way of storing it?

How you write it at work

At work a graph is nearly always a dict of containers:

  • defaultdict(list): the most common. Append is O(1); an edge added twice is stored twice.
  • defaultdict(set): drops repeated edges by itself and makes v in graph[u] O(1); the price is that a set has no order, so the walk order is not fixed (sort before printing).
  • defaultdict(dict): a weighted graph, graph[u][v] = w.
  • A vertex with no edges never shows up in the dict by itself: to count vertices, put all of them in first.
main.py
1edges = [("a", "b"), ("b", "c"), ("a", "b")]      # a–b appears twice2nodes = ["a", "b", "c", "d"]                      # d has no edges3 4graph = {u: set() for u in nodes}                 # every vertex first5for u, v in edges:6    graph[u].add(v)7    graph[v].add(u)8 9print(len(graph), sorted(graph["b"]), sorted(graph["d"]))10print("edge between a and c:", "c" in graph["a"])11print(graph.get("z", set()))                      # a vertex that isn't there: no key added
Output
4 ['a', 'c'] []
edge between a and c: False
set()

The standard library has no "graph" type: a dict of lists or sets is enough. For heavier graph analysis (PageRank, community detection) there is the third-party library networkx, which is a dict of dicts inside as well.

Guess the outputA wrong guess is fine

Neighbours kept in sets, and the edge a–b appears twice. What does this print?

1graph = {u: set() for u in "abc"}2for u, v in [("a", "b"), ("a", "b"), ("b", "c")]:3    graph[u].add(v)4    graph[v].add(u)5print(len(graph["a"]), sorted(graph["b"]))

Summary

Take-away

Two ways to store a graph

  • Adjacency matrix: an n × n 2D list; "is there an edge" is O(1), space O(n²), neighbours mean scanning a row
  • Adjacency list: a list of neighbours per vertex; space O(n + e), walking the graph O(n + e)
  • An undirected edge goes in at both ends; a directed one only as u -> v, in-degree counted apart
  • A weighted graph is a dict of dicts: graph[u][v] = w
  • Reading a defaultdict adds the key: use get or in just to look
1graph = defaultdict(list)2for u, v in edges:3    graph[u].append(v)4    graph[v].append(u)5matrix = [[0] * n for _ in range(n)]