Think about memory usage and efficiency when edges are few.
An adjacency list uses less memory and is more efficient for sparse graphs because it stores only existing edges. An adjacency matrix always uses space proportional to the square of the number of vertices, which is wasteful for sparse graphs.
Think about constant time edge lookup.
An adjacency matrix allows checking if an edge exists between two vertices in constant time O(1), which is faster than adjacency lists that may require searching through neighbors.
n = 3 adj_matrix = [[0]*n for _ in range(n)] adj_matrix[0][1] = 1 adj_matrix[1][2] = 1 adj_matrix[2][0] = 1 for row in adj_matrix: print(row)
Check which rows and columns have 1s based on edges.
The adjacency matrix has 1 at positions where an edge exists from row vertex to column vertex. So (0->1) sets adj_matrix[0][1] = 1, etc.
n = 3 adj_list = {i: [] for i in range(n)} adj_list[0].append(2) adj_list[0].append(1) adj_list[1].append(2) for key in sorted(adj_list.keys()): print(f"{key}: {adj_list[key]}")
Check the order of append operations for vertex 0.
Edges are added in order: 0->2 then 0->1, so adjacency list for 0 is [2, 1]. Vertex 1 has [2], vertex 2 has no edges.
Consider the size of adjacency matrix as vertices squared.
An adjacency matrix for 1 million vertices requires 1 trillion entries, which is huge. An adjacency list stores only 10 million edges, much smaller and efficient for sparse graphs.
