PythonMastery

Transpose a matrix in Python

Swap the rows and columns of a matrix stored as a list of lists, first with nested loops, then in one line with zip(*matrix).

To transpose a matrix, you turn its rows into columns: the first row becomes the first column, and so on. A matrix with 2 rows and 3 columns becomes one with 3 rows and 2 columns.

The program

python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
]

rows = len(matrix)
cols = len(matrix[0])

transposed = []
for c in range(cols):
    new_row = []
    for r in range(rows):
        new_row.append(matrix[r][c])
    transposed.append(new_row)

for row in transposed:
    print(row)
output
[1, 4]
[2, 5]
[3, 6]

How it works

Another way: zip(*matrix)

*matrix passes each row to zip() as a separate argument. zip() then takes the first item of every row, then the second item of every row, and so on. Those groups are exactly the columns:

python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
]

transposed = [list(column) for column in zip(*matrix)]
print(transposed)
print([list(column) for column in zip(*[])])
output
[[1, 4], [2, 5], [3, 6]]
[]

zip() gives tuples, so list(column) turns each one back into a list. An empty matrix gives an empty result here, with no error. If rows have different lengths, zip() stops at the shortest row without any error, so extra items are dropped.

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns, Comprehensions: Lists, Dicts, Sets, Generators