List vs Matrix
Graphs: lesson 2 of 8
Store the edges you have, or a cell for every pair you don't.
Lesson 2 of 8 · 5 min
List vs Matrix
Step 1 of 11
matrix
GKDFMFFW
GKDFMFFW
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
list
GK→[ ]
DF→[ ]
MF→[ ]
FW→[ ]
One graph, two ways to write it down. Four positions, four directed passes.
The Idea
Two ways to store the same graph. An adjacency list keeps, per node, only the neighbours it actually has — small when edges are scarce. An adjacency matrix reserves a cell for every possible pair, so "is A joined to B?" is one lookup, but blanks dominate.
Real-World Example
Football analysts log who passed to whom. Storing an eleven-by-eleven grid is fine, and instant to query, but scale it to every player in a league and almost every cell reads zero. Per-player pass lists hold the same information in a fraction of the space.
The Code
players = ["GK", "DF", "MF", "FW"]
passes = [("GK", "DF"), ("DF", "MF"), ("MF", "FW"), ("MF", "DF")]
adj = {p: [] for p in players} # adjacency list
for a, b in passes:
adj[a].append(b) # directed: a passed to b
idx = {p: i for i, p in enumerate(players)}
mat = [[0] * len(players) for _ in players] # adjacency matrix
for a, b in passes:
mat[idx[a]][idx[b]] = 1
print(adj["MF"]) # ['FW', 'DF']
print(mat[idx["MF"]]) # [0, 1, 0, 1]
Your turn
Fill in the blank.
adj = {"MF": [], "FW": []}
adj["MF"].___("FW") # record the pass MF -> FW
print(adj["MF"]) # ['FW']Mini quiz
1 / 3