Guide Python Intermediate

10.10 Nested Lists and Matrices

Creating, accessing, and updating nested lists using chained indices, iterating a 2D matrix row by row, and why [[0]*n]*n builds a matrix of shared, not independent, rows.

2 min read
flowchart TD M["matrix"] --> R0["row 0: [1, 2, 3]"] M --> R1["row 1: [4, 5, 6]"] M --> R2["row 2: [7, 8, 9]"]

matrix[1][2]6 — the first index selects the row, the second selects the column within it.

Create

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Access

Chain two indices: the first selects the row (inner list), the second selects the column within it.

>>> matrix[1][2]
6

Update

The same chained-index syntax works as an assignment target too.

>>> matrix[0][0] = 99
>>> matrix
[[99, 2, 3], [4, 5, 6], [7, 8, 9]]

Iterating a Matrix

A plain for loop over the outer list visits each row — the standard pattern for printing or processing a matrix.

>>> for row in matrix:
...     print(row)
[99, 2, 3]
[4, 5, 6]
[7, 8, 9]

Building a Matrix Correctly

A nested list comprehension is the correct way to build a matrix with genuinely independent rows:

>>> [[0 for _ in range(3)] for _ in range(3)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Quick Interview Answer

“A nested list represents a matrix by making each element of the outer list itself a list — matrix[row][col] chains two indices to reach a cell. The one genuine gotcha is construction: [[0] * 3] * 3 looks right but the outer * repeats references to the exact same inner list three times, so mutating one row mutates all of them. The safe way to build a matrix with independent rows is a nested list comprehension, [[0 for _ in range(3)] for _ in range(3)], which actually creates a fresh inner list on each outer iteration.”

Common Mistakes

  • Building a matrix with [[0] * cols] * rows — all rows are the same shared list object; matrix[0][0] = 1 changes every row, not just the first.
  • Confusing matrix[row][col] order with [col][row] — Python has no built-in convention beyond whatever the code defines; document which axis comes first.
  • Iterating with nested nested-index loops (for i in range(len(matrix)): for j in range(len(matrix[i])):) when a plain for row in matrix: (or enumerate() if the index is genuinely needed) is simpler and less error-prone.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form