Choose Graph Representations
Core idea
A graph contains vertices and edges. An adjacency list stores each vertex’s neighbors; a matrix stores one entry per ordered vertex pair. For a simple graph with V vertices and E edges, lists use O(V+E) space; a dense matrix uses O(V²) space and constant-time indexed edge lookup. Undirected edges appear in both directions.
graph = {v: [] for v in range(4)}for u, v in [(0, 1), (0, 2)]: graph[u].append(v) graph[v].append(u)print(graph)Vertex 3 is isolated but remains present.
Directed matrix
matrix = [[0]*3 for _ in range(3)]for u, v in [(0, 1), (1, 2)]: matrix[u][v] = 1print(matrix[0][1], matrix[1][0])An edge from 0 to 1 does not imply the reverse.
Common mistake
Creating rows using [[0]*V]*V aliases them. Use a comprehension. Keep isolated vertices even when they have no edges.
Practice
Represent a four-station directed network in both forms; compare memory when only two edges exist.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Graph representation
Check your understanding of graph representation.
What is printed?
g={0:[1],1:[],2:[]}print(len(g))What is printed?
m=[[0]*2 for _ in range(2)]m[0][1]=1print(m[1][0])Matrix space for V vertices?
Which is usually smaller for sparse graphs?