Transpose and the ragged-row pitfalls
A close cousin of column iteration is the transpose, which turns rows into columns by swapping the index roles. The nested list-comprehension form reads "for each new row c, take M[r][c] for every old row r":
M = [[1, 2, 3],
[4, 5, 6]]
T = [[M[r][c] for r in range(len(M))] for c in range(len(M[0]))]
# T == [[1, 4], [2, 5], [3, 6]]
Row sums, column sums, transpose, and matrix-by-vector products are all variations on the same nested-loop theme.
Two pitfalls dominate 2-D work in plain Python. The first is mixing up row and column order — M[r][c] versus M[c][r] — a bug that produces plausible-looking nonsense rather than an error.
The second is ragged data: nothing stops you building rows of unequal length, and then "the number of columns" is undefined and your loops break. Plain nested lists give no guarantee of a clean rectangle. NumPy fixes both shortly, with arrays that enforce a true rectangular shape and run these operations in fast compiled code — but the nested-loop reasoning you build here is what you'll express more concisely there.
leads into “Type hints and a numeric helper”.*
Related cards
Tasks
Card Info
- Topic: Python for Data Science
- Difficulty: Beginner
- Completed: 0 users