Python Program to Transpose a Matrix
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))] which flips rows and columns.Examples
How to Think About It
Algorithm
Code
matrix = [[1, 2], [3, 4]] transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))] print(transposed)
Dry Run
Let's trace the matrix [[1, 2], [3, 4]] through the code.
Original matrix
[[1, 2], [3, 4]]
Number of columns
len(matrix[0]) = 2
First iteration (i=0)
Collect elements at index 0 from each row: [1, 3]
Second iteration (i=1)
Collect elements at index 1 from each row: [2, 4]
Final transposed matrix
[[1, 3], [2, 4]]
| i | Collected elements |
|---|---|
| 0 | [1, 3] |
| 1 | [2, 4] |
Why This Works
Step 1: Access columns by index
We use range(len(matrix[0])) to loop over column indexes because the number of columns is the length of the first row.
Step 2: Collect elements from each row
For each column index, we pick the element at that index from every row using row[i].
Step 3: Build new rows
Each collection of elements from the same column forms a new row in the transposed matrix.
Alternative Approaches
matrix = [[1, 2], [3, 4]] transposed = list(map(list, zip(*matrix))) print(transposed)
matrix = [[1, 2], [3, 4]] transposed = [] for i in range(len(matrix[0])): new_row = [] for row in matrix: new_row.append(row[i]) transposed.append(new_row) print(transposed)
Complexity: O(m*n) time, O(m*n) space
Time Complexity
The program visits each element once to rearrange it, so the time grows with the number of elements (rows * columns).
Space Complexity
A new matrix of the same size is created to hold the transposed elements, so space also grows with the number of elements.
Which Approach is Fastest?
Using zip(*matrix) is usually fastest and most memory efficient in Python due to internal optimizations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List comprehension | O(m*n) | O(m*n) | Clear and Pythonic for beginners |
| zip with unpacking | O(m*n) | O(m*n) | Concise and efficient for Python users |
| Nested loops | O(m*n) | O(m*n) | Step-by-step clarity for learning |
zip(*matrix) for a quick and Pythonic transpose.