Transpose a matrix in Python
Rows become columns in one idiom.
def transpose(matrix):
if not matrix:
return []
return [list(row) for row in zip(*matrix)]
How it works
zip(*matrix)unpacks the rows as separate arguments.zipregroups them element-by-element into columns.- Each column tuple becomes a list.
Keywords and builtins used here
defforiflistreturntransposezip
The run, in numbers
- Lines
- 4
- Characters to type
- 90
- Tokens
- 28
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 18 seconds.
Step 7 of 10 in Collections, step 29 of 72 in Language basics.