typestar

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

  1. zip(*matrix) unpacks the rows as separate arguments.
  2. zip regroups them element-by-element into columns.
  3. Each column tuple becomes a list.

Keywords and builtins used here

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.

Type this snippet

Step 7 of 10 in Collections, step 29 of 72 in Language basics.

← Previous Next →