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
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)[1, 4] [2, 5] [3, 6]
How it works
matrix[r][c]is the item in rowr, columnc.- The outer loop goes through the columns. For each column, the inner loop collects the item from every row, and that list becomes one new row.
- So the new item at
[c][r]is the old item at[r][c]. - This code assumes every row has the same length, as rows in a matrix should. It also needs at least one row: for an empty list,
matrix[0]raises anIndexError.
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:
matrix = [
[1, 2, 3],
[4, 5, 6],
]
transposed = [list(column) for column in zip(*matrix)]
print(transposed)
print([list(column) for column in zip(*[])])[[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.