Transpose a small rectangular matrix with zip strict
Also published in our Blogger archive.
A matrix transpose turns rows into columns. For the two-by-three input [[1, 2, 3], [4, 5, 6]], the result is the three-by-two list [[1, 4], [2, 5], [3, 6]]. Calling zip(*rows, strict=True) advances one item from every row at a time, so each produced tuple is a column. The list comprehension then makes those columns mutable lists.
The strict=True argument matters when a rectangular shape is required. Ordinary zip stops at the shortest input without reporting that later values were discarded. Strict mode instead raises ValueError when one row ends before another, making a ragged matrix visible to the caller. It requires Python 3.10 or later; see the official zip documentation.
This example deliberately uses a small, already materialized matrix. It does not validate that rows is nonempty: an empty input transposes to an empty list, which may or may not suit an application. It also does not coerce elements or require numbers; transpose only rearranges positions. The assertion checks the intended result for this concrete fixture, while the printed list provides deterministic output.
AI assistance disclosure: this article was drafted with AI assistance and checked against the cited Python documentation.
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [list(column) for column in zip(*matrix, strict=True)]
assert transposed == [[1, 4], [2, 5], [3, 6]]
print(transposed)
[[1, 4], [2, 5], [3, 6]]