These are the notes for Python Coding Questions, episode 17: matrix questions. A matrix is a grid of values with rows (going across) and columns (going down). In Python, a matrix is a list of lists: a list of rows, where each row is a list of values, and m[r][c] is the value in row r, column c. First a trap that catches everyone when they create a grid, then three interview questions: transpose a matrix (with loops and with zip(*m)), rotate a square matrix 90° clockwise in place, and walk a matrix in spiral order. Every question has a non-square or edge case that breaks the obvious attempt, so test with rectangles, one row, one column and the empty matrix.
Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Every output below is real.
m = [[1, 2, 3],
[4, 5, 6]] # 2 rows, 3 columns
print(m[0]) # row 0
print(m[1][2]) # row 1, column 2
print(len(m), len(m[0])) # rows, columns
print([row[1] for row in m]) # column 1
Output:
[1, 2, 3]
6
2 3
[2, 5]
The trap: [[0] * n] * n
Real-life example: a cinema hall has rows of seats. One row is three seats side by side: in Python, [0, 0, 0] (0 = empty). The hall is three rows, one behind the other: a list of rows. To book a seat, you give the row first, then the seat: seats[0][0] = 1. The quick way to make the hall: a row, times three.
n = 3
seats = [[0] * n] * n # 3 rows of 3 empty seats
seats[0][0] = 1 # book the first seat only
print(seats)
print(seats[0] is seats[1])
Output:
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
True
We booked one seat, and the first seat of every row is booked. seats[0] is seats[1] is True: row 0 and row 1 are the same object.
Why
[0] * n makes one row. [row] * n doesn't copy that row: it makes a list holding the same row n times. Three names for one list: change it through one, and all three see it. ([0] * n itself is fine, because 0 is an immutable number: "changing" row[0] puts a new number in that position.)
row = [0, 0, 0]
hall = [row] * 3
print([id(r) == id(row) for r in hall])
row[2] = 7
print(hall)
Output:
[True, True, True]
[[0, 0, 7], [0, 0, 7], [0, 0, 7]]
The fix: a list comprehension
A list comprehension runs its expression again for each item, so [[0] * n for _ in range(n)] builds a new row every time. (_ is the usual name for a loop variable you don't use.)
n = 3
seats = [[0] * n for _ in range(n)] # a NEW row each time
seats[0][0] = 1
print(seats)
print(seats[0] is seats[1])
Output:
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
False
The same trap appears when copying a matrix: m.copy() or m[:] copies only the outer list; the rows are still shared. Copy each row, or use copy.deepcopy:
import copy
m = [[1, 2], [3, 4]]
shallow = m.copy()
rows_copied = [row[:] for row in m]
deep = copy.deepcopy(m)
m[0][0] = 99
print(shallow, rows_copied, deep)
Output:
[[99, 2], [3, 4]] [[1, 2], [3, 4]] [[1, 2], [3, 4]]
Q1: Transpose a matrix
Real-life example: a class timetable has one row per day and one column per period. A teacher wants it the other way round: one row per period, showing every day. Rows become columns and columns become rows. That's the transpose: the value at row r, column c moves to row c, column r. A grid of 2 rows × 3 columns becomes 3 rows × 2 columns. On a square grid, it's a flip across the main diagonal (top-left to bottom-right).
| Input | Output |
|---|---|
[[1, 2, 3], [4, 5, 6]] |
[[1, 4], [2, 5], [3, 6]] |
[[1, 2], [3, 4]] |
[[1, 3], [2, 4]] |
[[7]] |
[[7]] |
[[1, 2, 3]] (one row) |
[[1], [2], [3]] |
Attempt 1: two loops with one size
m = [[1, 2, 3],
[4, 5, 6]] # 2 rows, 3 columns
t = []
for i in range(len(m)):
row = []
for j in range(len(m)):
row.append(m[j][i])
t.append(row)
print(t)
Output:
[[1, 4], [2, 5]]
[[1, 4], [2, 5]]: where are 3 and 6? The answer should have three rows. No error, just missing data.
Why it fails
len(m) is the number of rows (2). But the transpose needs one row per column of m (3). We used one size for both, which only works when the grid is square. (With more rows than columns, the same code crashes with IndexError: list index out of range, because m[j][i] reaches past the end of a short row.)
m = [[1, 2], [3, 4], [5, 6]] # 3 rows, 2 columns
t = []
for i in range(len(m)):
row = []
for j in range(len(m)):
row.append(m[j][i])
t.append(row)
print(t)
Output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
row.append(m[j][i])
~~~~^^^
IndexError: list index out of range
The fix: name both sizes
rows = len(m), cols = len(m[0]). The transpose has cols rows, and t[c][r] = m[r][c]. A nested comprehension says it in one line: for each column c, the list of m[r][c] for every row r.
zip walks several lists side by side and pairs up their first items, then their second items, and so on: exactly a column. *m unpacks the rows as separate arguments, so zip(*m) is zip([1, 2, 3], [4, 5, 6]).
m = [[1, 2, 3],
[4, 5, 6]]
rows, cols = len(m), len(m[0])
t = [[m[r][c] for r in range(rows)] for c in range(cols)]
print(t) # 3 rows, 2 columns
print(list(zip(*m))) # zip(*m) gives the columns
print([list(col) for col in zip(*m)])
Output:
[[1, 4], [2, 5], [3, 6]]
[(1, 4), (2, 5), (3, 6)]
[[1, 4], [2, 5], [3, 6]]
zip gives tuples; list(col) turns each into a list. Edge cases:
def transpose(m):
return [list(col) for col in zip(*m)]
print(transpose([[1, 2, 3]]))
print(transpose([[1], [2], [3]]))
print(transpose([]))
print(transpose([[1, 2, 3], [4, 5]])) # ragged: zip stops at the shortest row
Output:
[[1], [2], [3]]
[[1, 2, 3]]
[]
[[1, 4], [2, 5]]
The last one is a ragged matrix (rows of different lengths): zip silently stops at the shortest row, so the 3 is dropped. If ragged input is possible, check all(len(row) == cols for row in m) first, or use itertools.zip_longest.
Complexity: O(rows × cols) time and space: every value moves once.
Q2: Rotate a square matrix 90° clockwise, in place
Real-life example: a photo on your phone came out sideways. You tap rotate, and every pixel moves. In place means: no second grid, change this one (images can be huge, so extra memory matters).
| Input | Output |
|---|---|
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
[[7, 4, 1], [8, 5, 2], [9, 6, 3]] |
[[1, 2], [3, 4]] |
[[3, 1], [4, 2]] |
[[5]] |
[[5]] |
The plan: a clockwise rotation is a transpose (flip across the diagonal) followed by mirroring each row (left ↔ right). The first column, 1, 4, 7, becomes the first row after the transpose, and reversed it's 7, 4, 1: the first row of the rotated photo.
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t = [list(col) for col in zip(*m)]
print("transpose:", t)
print("reversed rows:", [row[::-1] for row in t])
Output:
transpose: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
reversed rows: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
To transpose in place, swap m[i][j] with m[j][i]. Python swaps two values in one line: a, b = b, a.
Attempt 1: swap every i, j
m = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
n = len(m)
for i in range(n):
for j in range(n):
m[i][j], m[j][i] = m[j][i], m[i][j] # swap across the diagonal
print(m)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Exactly the same matrix. Nothing moved.
Why it fails
When i = 0, j = 1, we swap 2 and 4. Later, when i = 1, j = 0, we swap the same pair back. Every pair is swapped twice, which undoes it. (And when i == j, a cell is swapped with itself.)
The fix: swap each pair once, then reverse the rows
Only visit the cells above the diagonal: j starts at i + 1. Then row.reverse() mirrors each row in place.
def rotate(m):
n = len(m)
for i in range(n):
for j in range(i + 1, n): # only above the diagonal
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
row.reverse() # then mirror each row
return m
print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
print(rotate([[1, 2], [3, 4]]))
print(rotate([[5]]))
print([list(r) for r in zip(*[[1, 2, 3], [4, 5, 6]][::-1])]) # any shape, new list
Output:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
[[3, 1], [4, 2]]
[[5]]
[[4, 1], [5, 2], [6, 3]]
The last line is the one-liner for when a new list is fine (or the matrix isn't square, since a non-square matrix can't be rotated in place: its shape changes). m[::-1] reverses the order of the rows, then zip(*...) reads the columns: [[4, 1], [5, 2], [6, 3]].
Why does the in-place version need a square? A 2 × 3 matrix rotated is 3 × 2: it doesn't fit in the same rows. In-place rotation is only defined for n × n.
Does the in-place version really change the caller's matrix? Yes: lists are passed by reference, so the function works on the same object.
def rotate(m):
n = len(m)
for i in range(n):
for j in range(i + 1, n):
m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m:
row.reverse()
photo = [[1, 2], [3, 4]]
before = id(photo)
rotate(photo)
print(photo, id(photo) == before)
Output:
[[3, 1], [4, 2]] True
Complexity: O(n²) time (every cell is touched a constant number of times), O(1) extra space for the in-place version. The zip one-liner uses O(n²) extra space.
Other rotations
- Anticlockwise 90°: transpose, then reverse the order of the rows (instead of each row). One-liner:
[list(r) for r in zip(*m)][::-1]. - 180°: reverse the rows' order and each row:
[row[::-1] for row in m[::-1]].
Q3: Spiral order
Real-life example: a security guard checks a parking lot laid out in a grid of spots once every night. He walks the outer ring clockwise: right along the top, down the right side, left along the bottom, up the left side. Then the next ring in, until every spot has been checked once.
| Input | Output |
|---|---|
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
[1, 2, 3, 6, 9, 8, 7, 4, 5] |
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] |
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] |
[[1, 2, 3]] |
[1, 2, 3] |
[[1], [2], [3]] |
[1, 2, 3] |
[] |
[] |
In code: four boundaries ("walls"): top and bottom (row numbers), left and right (column numbers). After walking along a wall, move that wall one step inward. Stop when the walls cross.
Attempt 1: four walks per ring
def spiral(m):
out = []
top, bottom = 0, len(m) - 1
left, right = 0, len(m[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1): # right along the top
out.append(m[top][c])
top += 1
for r in range(top, bottom + 1): # down the right side
out.append(m[r][right])
right -= 1
for c in range(right, left - 1, -1): # left along the bottom
out.append(m[bottom][c])
bottom -= 1
for r in range(bottom, top - 1, -1): # up the left side
out.append(m[r][left])
left += 1
return out
print(spiral([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
print(spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
print(spiral([[1, 2, 3]]))
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6]
[1, 2, 3, 2, 1]
range(right, left - 1, -1) counts down from right to left (the stop value is not included, so we stop at left - 1). The 3 × 3 is right. But the 3 × 4 ends with 7, 6: 6 twice. And one row gives [1, 2, 3, 2, 1].
Why it fails
Take the single row [[1, 2, 3]]: top = bottom = 0. After the top walk, top becomes 1, which is past bottom. There is no bottom row any more, but the loop walks it anyway, backwards over the same cells: 2, 1. The walls are only checked at the start of each ring (while ...), but they can cross in the middle of a ring.
The fix: re-check before walking back
The first two walks are always safe. Before the bottom walk, check top <= bottom (a bottom row is still left). Before the left walk, check left <= right (a left column is still left). And an empty matrix has no m[0], so return [] first.
def spiral(m):
if not m:
return []
out = []
top, bottom = 0, len(m) - 1
left, right = 0, len(m[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(m[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(m[r][right])
right -= 1
if top <= bottom: # a bottom row is still left
for c in range(right, left - 1, -1):
out.append(m[bottom][c])
bottom -= 1
if left <= right: # a left column is still left
for r in range(bottom, top - 1, -1):
out.append(m[r][left])
left += 1
return out
print(spiral([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
print(spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
print(spiral([[1, 2, 3]]), spiral([[1], [2], [3]]), spiral([]))
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
[1, 2, 3] [1, 2, 3] []
Every number exactly once. A good self-check: the output must have rows × cols items.
import random
def spiral(m):
if not m:
return []
out = []
top, bottom = 0, len(m) - 1
left, right = 0, len(m[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(m[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(m[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
out.append(m[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
out.append(m[r][left])
left += 1
return out
for rows in range(1, 7):
for cols in range(1, 7):
m = [[r * cols + c for c in range(cols)] for r in range(rows)]
assert sorted(spiral(m)) == list(range(rows * cols)), (rows, cols)
print("every shape from 1x1 to 6x6: each cell exactly once")
Output:
every shape from 1x1 to 6x6: each cell exactly once
assert condition, message stops the program with AssertionError if the condition is false. Testing every small shape like this is a cheap way to catch the edge cases you didn't think of.
Complexity: O(rows × cols) time: each cell is visited once. O(1) extra space besides the output list (four numbers for the walls).
Common mistakes (and what you really see)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
[[0] * n] * n |
[[1, 0, 0], [1, 0, 0], [1, 0, 0]] after one booking |
the same row, n times | [[0] * n for _ in range(n)] |
m.copy() to copy a matrix |
changing the copy changes m |
rows are shared | [row[:] for row in m] or copy.deepcopy |
range(len(m)) for both transpose loops |
2×3 → [[1, 4], [2, 5]]; 3×2 → IndexError: list index out of range |
rows ≠ columns | cols = len(m[0]) |
forgetting list() around zip |
[(1, 4), (2, 5), (3, 6)]: tuples |
zip gives tuples |
[list(c) for c in zip(*m)] |
zip(*m) on a ragged matrix |
values silently dropped | zip stops at the shortest |
check row lengths, or zip_longest |
swap m[i][j], m[j][i] for all i, j |
the matrix is unchanged | each pair swapped twice | j from i + 1 |
| transpose only | a flip, not a rotation | half the job | then reverse each row |
| reverse the rows' order instead of each row | an anticlockwise rotation | the wrong mirror | row.reverse() for clockwise |
| spiral without re-checks | [[1, 2, 3]] → [1, 2, 3, 2, 1] |
walls cross mid-ring | if top <= bottom / if left <= right |
len(m[0]) on [] |
IndexError: list index out of range |
no first row | if not m: return [] |
Here are two of them run for real:
m = []
print(len(m))
print(len(m[0]))
Output:
0
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(len(m[0]))
~^^^
IndexError: list index out of range
m = [[1, 2], [3, 4]]
copy_ = m.copy()
copy_[0][0] = 99
print(m)
Output:
[[99, 2], [3, 4]]
Your turn: set matrix zeroes (solution)
Wherever a cell is 0, set its whole row and its whole column to 0. [[1, 2, 3], [4, 0, 6], [7, 8, 9]] → [[1, 0, 3], [0, 0, 0], [7, 0, 9]]. The trap: zeroes you write while you're still scanning make more rows and columns zero.
Solution
First the trap, for real: zeroing while scanning.
def set_zeroes_wrong(m):
for r in range(len(m)):
for c in range(len(m[0])):
if m[r][c] == 0:
for k in range(len(m[0])):
m[r][k] = 0
for k in range(len(m)):
m[k][c] = 0
return m
print(set_zeroes_wrong([[1, 2, 3], [4, 0, 6], [7, 8, 9]]))
Output:
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Everything after the first zero became zero, because the scan kept finding the zeroes we had just written. The fix: two passes. First only record which rows and columns contain a zero (in two sets), then zero them.
def set_zeroes(m):
zero_rows, zero_cols = set(), set()
for r, row in enumerate(m):
for c, value in enumerate(row):
if value == 0:
zero_rows.add(r)
zero_cols.add(c)
for r, row in enumerate(m):
for c in range(len(row)):
if r in zero_rows or c in zero_cols:
row[c] = 0
return m
print(set_zeroes([[1, 2, 3], [4, 0, 6], [7, 8, 9]]))
print(set_zeroes([[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]))
print(set_zeroes([[1, 2], [3, 4]]))
Output:
[[1, 0, 3], [0, 0, 0], [7, 0, 9]]
[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
[[1, 2], [3, 4]]
O(rows × cols) time, O(rows + cols) extra space for the two sets. (An O(1)-space version stores the markers in the first row and column of the matrix itself; it's a common follow-up.)
Practice questions (with solutions)
1. Rotate 90° anticlockwise.
Solution
Transpose, then reverse the order of the rows (clockwise reversed each row instead).
def rotate_anticlockwise(m):
return [list(r) for r in zip(*m)][::-1]
print(rotate_anticlockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
print(rotate_anticlockwise([[1, 2, 3], [4, 5, 6]]))
Output:
[[3, 6, 9], [2, 5, 8], [1, 4, 7]]
[[3, 6], [2, 5], [1, 4]]
2. Print the two diagonals of a square matrix, and their sum.
Solution
The main diagonal is m[i][i]; the other ("anti") diagonal is m[i][n - 1 - i]. For an odd n, the middle cell is on both, so subtract it once when adding.
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = len(m)
main = [m[i][i] for i in range(n)]
anti = [m[i][n - 1 - i] for i in range(n)]
total = sum(main) + sum(anti) - (m[n // 2][n // 2] if n % 2 else 0)
print(main, anti, total)
Output:
[1, 5, 9] [3, 5, 7] 25
3. Search a matrix whose rows and columns are sorted, in O(rows + cols).
Solution
Start at the top-right corner. If the value is too big, everything below it in that column is bigger too: move left. If it's too small, everything to its left is smaller: move down. Each step throws away a whole row or column.
def search(m, target):
if not m:
return False
r, c = 0, len(m[0]) - 1
while r < len(m) and c >= 0:
if m[r][c] == target:
return (r, c)
if m[r][c] > target:
c -= 1 # too big: this column is out
else:
r += 1 # too small: this row is out
return False
m = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]]
print(search(m, 5), search(m, 14), search(m, 15), search([], 1))
Output:
(1, 1) (3, 2) False False
4. Build an n × n spiral matrix filled with 1 to n².
Solution
The same four walls, but writing instead of reading. Create the grid with a comprehension (not [[0] * n] * n!).
def spiral_fill(n):
m = [[0] * n for _ in range(n)]
top, bottom, left, right = 0, n - 1, 0, n - 1
k = 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
m[top][c] = k; k += 1
top += 1
for r in range(top, bottom + 1):
m[r][right] = k; k += 1
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
m[bottom][c] = k; k += 1
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
m[r][left] = k; k += 1
left += 1
return m
for row in spiral_fill(4):
print(row)
Output:
[1, 2, 3, 4]
[12, 13, 14, 5]
[11, 16, 15, 6]
[10, 9, 8, 7]
5. Matrix multiplication. Multiply a 2 × 3 matrix by a 3 × 2 matrix.
Solution
Entry (i, j) of the product is row i of a "dotted" with column j of b: multiply matching items and add. zip(*b) gives b's columns. The number of columns of a must equal the number of rows of b.
def matmul(a, b):
if len(a[0]) != len(b):
raise ValueError("columns of a must equal rows of b")
return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)] for row in a]
a = [[1, 2, 3], [4, 5, 6]]
b = [[7, 8], [9, 10], [11, 12]]
print(matmul(a, b))
Output:
[[58, 64], [139, 154]]
O(n³) for two n × n matrices.
Quick quiz
What does this print?
m = [[1, 2], [3, 4], [5, 6]]
print(list(zip(*m))[1])
print(len(m), len(m[0]))
(A) (3, 4) then 3 2 (B) (2, 4, 6) then 3 2 (C) (2, 4, 6) then 2 3 (D) [3, 4] then 2 3
Answer
(B). zip(*m) pairs up the rows' items position by position, so it gives the columns: (1, 3, 5) and (2, 4, 6). Index 1 is the second column, (2, 4, 6), a tuple. zip doesn't change m: still 3 rows of 2.
m = [[1, 2], [3, 4], [5, 6]]
print(list(zip(*m))[1])
print(len(m), len(m[0]))
Output:
(2, 4, 6)
3 2
Interview questions
- Why does
[[0] * n] * nbehave strangely? The outer* nrepeats a reference to the same inner list, so writing to one row writes to all. Use[[0] * n for _ in range(n)]. - How do you transpose a matrix in Python?
[list(c) for c in zip(*m)], or a nested comprehension[[m[r][c] for r in range(rows)] for c in range(cols)]. O(rows × cols). - What does
zip(*m)do?*mpasses each row as a separate argument;zipgroups the items at each position, giving the columns as tuples. It stops at the shortest row. - How do you rotate an n × n matrix 90° clockwise in place? Transpose by swapping
m[i][j]andm[j][i]forj > ionly, then reverse each row. O(n²) time, O(1) extra space. - Why does swapping for all
i, jdo nothing? Each pair is swapped twice (once as(i, j), once as(j, i)), which restores it. - How would you rotate anticlockwise? Transpose, then reverse the order of the rows; or reverse each row first, then transpose.
- How do you print a matrix in spiral order? Keep four boundaries (
top,bottom,left,right); walk the top row, right column, bottom row and left column, moving each boundary inward; re-checktop <= bottomandleft <= rightbefore the bottom and left walks. O(rows × cols). - What are the spiral edge cases? One row, one column, an empty matrix, and non-square rectangles (3 × 4, 4 × 3).
- How do you copy a matrix?
[row[:] for row in m]orcopy.deepcopy(m);m.copy()shares the rows. - Why can't a 2 × 3 matrix be rotated in place? Its rotation is 3 × 2: a different shape needs a new list.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Matrix | A grid of values with rows and columns | a seating plan |
| List of lists | Python's usual matrix: a list of rows | [[1, 2], [3, 4]] |
| Row / column | A line across / a line down | m[0] / [row[0] for row in m] |
m[r][c] |
The value in row r, column c | m[1][2] |
| Square matrix | Same number of rows and columns (n × n) | 3 × 3 |
| Ragged matrix | Rows of different lengths | [[1, 2, 3], [4, 5]] |
| Reference | A name or list slot pointing to an object | [row] * 3 holds 3 references to one row |
is |
True if two names are the same object | seats[0] is seats[1] |
id() |
An object's identity number | id(row) |
| List comprehension | Builds a list, running the expression for each item | [[0] * n for _ in range(n)] |
_ |
The usual name for an unused loop variable | for _ in range(3) |
| Shallow copy | Copies the outer list, shares the rows | m.copy(), m[:] |
| Deep copy | Copies every level | copy.deepcopy(m) |
| Transpose | Rows become columns: t[c][r] = m[r][c] |
2 × 3 → 3 × 2 |
| Main diagonal | The cells m[i][i], top-left to bottom-right |
1, 5, 9 |
| Anti-diagonal | The cells m[i][n - 1 - i] |
3, 5, 7 |
zip |
Walks iterables side by side, grouping items by position | zip([1, 2], [3, 4]) → (1, 3), (2, 4) |
* unpacking (arguments) |
Passes a list's items as separate arguments | zip(*m) |
| Tuple | An immutable sequence | (1, 4) |
| Rotate 90° clockwise | Transpose, then reverse each row | [[7, 4, 1], ...] |
| In place | Changing the object itself, no new copy | row.reverse() |
row.reverse() / row[::-1] |
Reverse in place / a reversed copy | |
| Swap | a, b = b, a |
m[i][j], m[j][i] = m[j][i], m[i][j] |
| O(1) extra space | Memory that doesn't grow with the input | four wall variables |
| Spiral order | Visiting the outer ring clockwise, then the next ring in | 1 2 3 6 9 8 7 4 5 |
| Boundary / wall | The current edge row or column of the unvisited part | top, bottom, left, right |
range(a, b, -1) |
Counts down from a to b + 1 | range(3, -1, -1) → 3, 2, 1, 0 |
assert |
Stops with AssertionError if a condition is false |
assert len(out) == rows * cols |
IndexError |
No item at that position | [][0] |
| Edge case | An unusual input that often breaks code | one row, one column, [] |
| Matrix multiplication | Row of a dotted with column of b | matmul(a, b) |
Summary
- The trap:
[[0] * n] * nputs the same row in the list n times, so booking one seat changed every row. Build grids with[[0] * n for _ in range(n)], and copy them with[row[:] for row in m]orcopy.deepcopy. - Transpose: rows and columns are different sizes:
rows = len(m),cols = len(m[0]). One size for both lost3and6.[list(c) for c in zip(*m)]gives the columns. O(rows × cols). - Rotate 90° clockwise in place: swapping every
(i, j)swaps each pair twice and changes nothing. Swap onlyj > i(the transpose), then reverse each row. O(n²) time, O(1) extra space. Any shape, new list:zip(*m[::-1]). - Spiral order: four walls moving inward. The walls can cross in the middle of a ring, so re-check
top <= bottombefore the bottom walk andleft <= rightbefore the left walk (otherwise one row gave[1, 2, 3, 2, 1]), and return[]for an empty matrix. O(rows × cols).
Next episode: Function questions: the mutable default argument trap, writing your own timing decorator, and memoizing with a dictionary versus functools.lru_cache.