Multidimensional Lists (Matrices)
Introduction
In Python, a 2D array (matrix) is simply a list of lists.
You will use 2D lists heavily in Graph problems (adjacency matrices), Dynamic Programming (2D memoization tables), and Grid traversal problems (like Islands or Mazes).
The Danger of [[0] * C] * R
The most common bug in Python coding interviews is initializing a 2D matrix incorrectly.
❌ Incorrect Initialization:
If you printmatrix, it looks correct:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
But if you modify one element:
Output:[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Why?
The outer multiplication * R copied the reference to the inner list \(R\) times. There is only one inner list in memory, and every row points to it.
The Correct Way: List Comprehensions
To properly initialize a matrix, you must create a new inner list on every iteration. Use a list comprehension.
✅ Correct Initialization:
Now, modifying one cell works correctly:
Output:[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Memorize This Pattern
Iterating Over a Matrix
1. By Index
Use this when you need the coordinates \((r, c)\) for logic.
2. By Value
Use this when you only need to read the values.
3. Both (Using enumerate)
Accessing Columns
To extract a specific column from a matrix, use a list comprehension. (Unlike NumPy, standard Python lists don't support matrix[:, c]).
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Extract column index 1
col = [row[1] for row in matrix]
print(col) # [2, 5, 8]
Time and Space Complexity
- Time Complexity: \(O(R \times C)\) to initialize the matrix.
- Space Complexity: \(O(R \times C)\) to store the matrix.
Summary
- Never initialize a 2D list using
[[0] * C] * R. - Always use
[[0] * C for _ in range(R)]. - Know how to iterate through a matrix using nested loops and
enumerate.