Transpose and the ragged-row pitfalls

Beginner Python for Data Science
Created by Best · 24.06.2026 at 14:03 UTC

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”.*

University approvals: 0
Related cards
Builds on Matrices: indexing, row and column sums · Python for Data Science
Next Type hints and a numeric helper · Python for Data Science
Tasks
Question 1

What does transposing a matrix do?

Question 2

A nested list is called "ragged" when...

Card Info
  • Topic: Python for Data Science
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy