Sub topic 8
Transposing a Matrix
This chapter assumes you can index a nested list with grid[r][c], write nested for loops, and use list comprehensions. It covers what a transpose is, two ways to compute it in Python, and the errors that come up most often.
What a transpose does
The transpose of a matrix swaps its rows and columns. The element at row r, column c moves to row c, column r. An m by n matrix becomes an n by m matrix. The first row of the original becomes the first column of the result.
Transposing with nested loops
The direct approach builds a new matrix with swapped dimensions, then copies each cell to its swapped position.
def transpose(grid):
rows, cols = len(grid), len(grid[0])
result = [[0] * rows for _ in range(cols)]
for r in range(rows):
for c in range(cols):
result[c][r] = grid[r][c]
return result
grid = [[1, 2, 3], [4, 5, 6]]
print(transpose(grid)) # [[1, 4], [2, 5], [3, 6]]The result has cols rows and rows columns. Getting these two numbers backwards is the most common mistake. The result is built with a comprehension, so each row is its own list (see the shared-row pitfall in the creation chapter).
Transposing with zip
Python has a shorter form:
grid = [[1, 2, 3], [4, 5, 6]]
transposed = [list(col) for col in zip(*grid)]
print(transposed) # [[1, 4], [2, 5], [3, 6]]Here is how it works:
*gridunpacks the rows, sozipreceives[1, 2, 3]and[4, 5, 6]as separate arguments.zippairs up the first items, then the second items, then the third. That produces the tuples(1, 4),(2, 5),(3, 6).list(col)turns each tuple into a list, so the result is a list of lists that you can modify.
zip stops at the shortest row. If the rows have different lengths, it silently drops the extra items. The nested-loop version would fail with an IndexError or produce wrong shapes instead, so check that the rows are the same length first.
In-place transpose of a square matrix
When the matrix is square (n by n), you can transpose it without a second matrix. Swap each cell above the diagonal with its mirror cell below it.
def transpose_in_place(grid):
n = len(grid)
for r in range(n):
for c in range(r + 1, n):
grid[r][c], grid[c][r] = grid[c][r], grid[r][c]
square = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose_in_place(square)
print(square) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]The inner loop starts at r + 1. If it started at 0, every pair would be swapped twice and the matrix would end up unchanged. Diagonal cells, where r == c, stay where they are, so the loop skips them.
A non-square matrix cannot be transposed in place this way, because the result has a different shape from the original.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `IndexError` in the loop version | The result was created as `rows` by `cols` instead of `cols` by `rows` | Use `cols` for the number of result rows |
| Unchanged square matrix | The in-place loop visits every pair twice | Start the inner loop at `r + 1` |
| Rows change together | The result was built with `[[0] * rows] * cols` | Use a comprehension |
| Data silently lost | `zip` was used on rows of unequal length | Validate row lengths first |
Cost
Every cell is visited once, so the time cost is O(m·n). The copying versions also use O(m·n) extra space. The in-place version for square matrices uses O(1) extra space.
Exercise
What is the shape of the transpose of a matrix with 4 rows and 7 columns? Then write the expression that gives the cell of the result at row 5, column 2 in terms of the original grid.
Show answer
The transpose has 7 rows and 4 columns. The result cell at row 5, column 2 is grid[2][5], because transposing swaps the two indices.
Exercise
The following in-place transpose leaves a square matrix unchanged. Why, and how do you fix it? for r in range(n): for c in range(n): grid[r][c], grid[c][r] = grid[c][r], grid[r][c]
Show answer
Each pair of mirror cells is swapped twice, once when r < c and once when r > c, so the second swap undoes the first. Change the inner loop to for c in range(r + 1, n): so each pair is swapped once.