Lists
Nested Lists
2D lists and matrices
Interview: Matrix/grid problems are among the most common interview questions
Nested lists (lists of lists) are Python's simplest way to represent 2D data like matrices, grids, and tables. While they work well for small datasets, understanding the shared reference pitfall is critical for correct usage.
Creating 2D Lists
- Literal:
[[1, 2], [3, 4]]— explicit and safe - Comprehension:
[[0]*cols for _ in range(rows)]— correct way for dynamic sizes - DANGER:
[[0]*3]*3creates 3 references to the SAME inner list — modifying one row changes all rows! - Why:
[x]*ncreates n references to x, not n copies
Accessing and Iterating
- Element access:
matrix[row][col] - Row iteration:
for row in matrix: - All elements: Nested for loops with row/col indices
- Flattening:
[x for row in matrix for x in row]
Common Matrix Operations
- Transpose:
list(map(list, zip(*matrix)))or nested comprehension - Row/column sums: Use list comprehension with sum()
- Rotation: Transpose + reverse each row (for 90-degree clockwise)
- For production: Use NumPy for numerical matrices — it's faster and more feature-rich
The #1 Pitfall
[[0]*3]*3 creates shared inner lists. Always use a comprehension: [[0]*3 for _ in range(3)]. The same applies to any mutable inner object.
Use Cases
Representing matrices for linear algebra and ML
Grid-based problems (mazes, game boards, image processing)
Tabular data before adopting pandas
Dynamic programming tables
Common Mistakes
Using [[0]*n]*m which creates shared inner lists — always use a comprehension
Assuming all inner lists have the same length (jagged arrays are valid in Python)
Using nested lists for numerical computation when NumPy is much faster
Forgetting boundary checks when accessing neighbors in grid problems