Intermediate 8 min

Adjacency lists and matrices

A graph can store each vertex’s neighbors as a list or record every possible connection in a matrix.

How it works

For four rooms, a matrix keeps 16 positions no matter how many corridors exist. A list keeps the room names and only the corridors that exist. Choose a matrix when you need quick checks for arbitrary pairs and space is acceptable. Choose lists when exploring neighbors is the main operation.

Walk through an example

For a graph with only a few edges per vertex, adjacency lists store mostly real edges. A matrix stores a cell for every ordered pair and makes checking one edge direct.

What to watch for

Decide whether edges are directed. In an undirected graph, an edge normally appears in both vertices’ neighbor lists.

Code example

graph = {'A': ['B'], 'B': ['A']}
print(graph['A'])

Check your understanding

Which neighbor lists change?

See the example and explanation
Worked example
Given An undirected graph has edge A—B.
Answer A gains B and B gains A.

The edge can be traversed in either direction, so both endpoints need the other endpoint as a neighbor.

Open practice problem
Next lessonCounting sort