The transpose of a matrix is a matrix with the column and row elements switched. For example, the transpose of [[1, 2], [3, 4]]
is [[1, 3], [2, 4]]
.
USE zip()
TO TRANSPOSE A MATRIX
Pass the rows of the matrix as separate lists to zip(*iterable)
using the *
operator. Use a loop to iterate through each row. For each row, call list(iterable)
on it and add the result into a new list that represents the transpose matrix.
matrix = [[1, 2], [3, 4]]
Example matrix
zipped_rows = zip(*matrix)
Zip into a list
transpose_matrix = [list(row) for row in zipped_rows]
Transpose matrix
print(transpose_matrix)
OUTPUT
[[1, 3], [2, 4]]
OTHER SOLUTIONS
- This solution is shorter and performs better with larger matrices. However, it requires use of the NumpPy library.