Two ways to store it
A directed graph: 5 vertices numbered 0 to 4 and 6 one-way edges, such as 3 → 4. Python receives it as an edge list of pairs. Algorithms need a shape they can ask questions of quickly: a list per vertex, or a grid.
Start with one empty Python list per vertex. For each edge (u, v), append v to adj[u]. Six edges, six appends: adj[3] ends up as [1, 4]. Each directed edge is stored once, in the list of the vertex it leaves.
The matrix starts as a 5 × 5 grid of zeros: 25 cells, made before any edge is read. Then each edge (u, v) sets mat[u][v] = 1. Row u shows where u’s edges go; column v shows where v’s edges come from.
The list holds 5 heads plus 6 entries: V + E = 11 slots. The matrix holds V × V = 25 cells, even with no edges. Lists grow with the edges; the matrix grows with the square of the vertices.
Asking questions
Ask: is there an edge from 3 to 4? The matrix goes straight to row 3, column 4 and reads one cell. It holds 1, so yes. One read, however big the graph: O(1) time.
The list must search. Python’s in walks adj[3] from the left: 1, no; 4, yes. That took 2 reads. At worst it reads every entry, so the cost is O(deg(u)), where deg(u) counts the edges leaving u.
Now list every vertex 3 points to. The list hands over adj[3] = [1, 4]: 2 reads. The matrix must read all 5 cells of row 3 to find its two 1s. That is O(deg(u)) against O(V).
Choosing
BFS and DFS ask that question for every vertex. With lists that is 5 heads plus 6 entries: 11 reads, O(V + E). With the matrix it is every cell: 25 reads, O(V²), even when most cells are 0.
Pick by density. A graph with 1,000 vertices and 3,000 edges needs a 1,000,000-cell matrix that is almost all zeros, but only 4,000 list slots. When E is close to V², or edge checks dominate, choose the matrix.
What happens
;; step 1/9 · the-graph edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1), (3, 4)] V = 5, E = 6 out-degree deg(u) = edges leaving u: deg(0) = 2 deg(1) = 1 deg(2) = 1 deg(3) = 2 deg(4) = 0 sum of out-degrees = 6 = E
The figure counts slots and cells, not bytes. A Python list of lists also stores pointers and spare room for appends, but the growth stays the same: Θ(V + E) for lists and Θ(V²) for the matrix. In an undirected graph every edge is stored twice, as v in adj[u] and u in adj[v], so the lists hold V + 2E slots, and the matrix is symmetric about its diagonal.