Transpose of a Matrix in Python: 3 Methods with Examples
Compute the transpose of a matrix in Python using zip(*matrix), nested loops, and NumPy .T. Includes a worked 3x4 example and placement-round guidance.
Transposing a matrix means swapping its rows and columns so that each element at row i, column j moves to row j, column i, turning an m×n matrix into an n×m matrix.
What Matrix Transpose Means
Given a matrix M with m rows and n columns, its transpose T has n rows and m columns. The defining rule is simple: T[j][i] = M[i][j] for every valid i and j.
For a square 3×3 matrix, this is equivalent to reflecting the matrix across its main diagonal. For non-square matrices, the shape itself changes.
Here is a 3×4 matrix and its 4×3 transpose worked out in full:
Original (3 rows, 4 columns):
| Col 0 | Col 1 | Col 2 | Col 3 | |
|---|---|---|---|---|
| Row 0 | 1 | 2 | 3 | 4 |
| Row 1 | 5 | 6 | 7 | 8 |
| Row 2 | 9 | 10 | 11 | 12 |
Transposed (4 rows, 3 columns):
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Row 0 | 1 | 5 | 9 |
| Row 1 | 2 | 6 | 10 |
| Row 2 | 3 | 7 | 11 |
| Row 3 | 4 | 8 | 12 |
Three spot-checks confirm the rule holds:
- Original
M[0][3] = 4appears at transposeT[3][0] = 4. - Original
M[2][1] = 10appears at transposeT[1][2] = 10. - Original
M[1][2] = 7appears at transposeT[2][1] = 7.
Matrix transpose appears in quantitative aptitude and programming sections of campus placement evaluation tests, particularly for roles at analytics, data engineering, and product companies. Questions typically ask you to print the transpose of a given matrix, check if a matrix is symmetric, or rotate it by 90 degrees. All three reduce to the same index-swap operation.
Method 1: zip(*matrix)
Python’s zip() function groups corresponding elements from multiple iterables. When you write zip(*matrix), the * operator unpacks the matrix into its individual rows, passing each row as a separate argument to zip(). The Python built-in zip() function then picks the first element from each row (forming the first column), the second element from each row (forming the second column), and so on. Each group becomes a tuple, which is exactly one row of the transposed matrix.
The full one-liner for the 3×4 matrix above:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
transposed = [list(row) for row in zip(*matrix)]
for row in transposed:
print(row)
# Output:
# [1, 5, 9]
# [2, 6, 10]
# [3, 7, 11]
# [4, 8, 12]
The list(row) call inside the list comprehension converts each tuple that zip() produces into a list. If tuples are acceptable (as they often are in placement submissions), you can simplify to list(zip(*matrix)).
Two things to keep in mind when using this approach. First, zip() stops at the shortest row. If the matrix has ragged rows (rows of unequal length), zip(*matrix) silently drops trailing elements. This is rarely a concern with well-formed input, but worth knowing for edge-case questions. Second, for large matrices, zip() returns a lazy iterator in Python 3, so memory usage stays low until you materialise the results.
For a 2×3 matrix (2 rows, 3 columns), the transpose is a 3×2 matrix:
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [list(row) for row in zip(*matrix)]
# [[1, 4], [2, 5], [3, 6]]
The output has 3 rows and 2 columns, as expected.
Method 2: Nested Loop with Pre-allocated Array
The nested-loop method makes the index-swap explicit. It is the approach to use when a placement or interview question specifically asks you to implement the transpose without using built-in functions.
The key design choice is pre-allocation: create an output array with the correct final shape first, then fill it. Pre-allocating n rows of m zeros each means every valid index transposed[j][i] is writable without appending.
def transpose_nested(matrix):
m = len(matrix) # original row count
n = len(matrix[0]) # original column count
# Pre-allocate a (n x m) array of zeros
transposed = [[0] * m for _ in range(n)]
for i in range(m):
for j in range(n):
transposed[j][i] = matrix[i][j]
return transposed
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
result = transpose_nested(matrix)
for row in result:
print(row)
# Output:
# [1, 5, 9]
# [2, 6, 10]
# [3, 7, 11]
# [4, 8, 12]
Walking through a single iteration to confirm the logic: when i = 0 and j = 3, the assignment is transposed[3][0] = matrix[0][3], which places the value 4 at row 3, column 0 of the transposed matrix. The worked example above shows T[3][0] = 4, which matches.
The pre-allocation pattern [[0] * m for _ in range(n)] deserves a second look. Writing [[0] * m] * n instead looks identical but creates n references to the same list object. Modifying one row then corrupts all rows. The list comprehension version creates n independent lists and avoids this pitfall entirely.
When explaining this approach in a technical interview, two things to mention: the time complexity is O(m*n) since every element is visited exactly once, and the space complexity is also O(m*n) for the output array. Neither method does better on space, because the transposed matrix must be stored somewhere.
Method 3: NumPy .T
For programs that already import NumPy (data analysis scripts, machine learning pipelines, scientific computing), matrix.T is the standard approach. It is a single attribute access, produces no intermediate loops, and is implemented in C.
import numpy as np
matrix = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
transposed = matrix.T
print(transposed)
# Output:
# [[ 1 5 9]
# [ 2 6 10]
# [ 3 7 11]
# [ 4 8 12]]
print(transposed.shape) # (4, 3)
The NumPy ndarray.T attribute returns a view into the original array with the axes reversed. No data is copied. The shape attribute confirms the result is a 4×3 array for a 3×4 input.
Because .T returns a view and not an independent copy, modifications to the transposed array affect the original. If you need to work with both independently:
transposed_copy = matrix.T.copy()
numpy.transpose(matrix) is the functional equivalent of matrix.T and accepts an optional axes parameter for higher-dimensional arrays. For two-dimensional matrices, both are identical.
NumPy is not available in every placement coding environment. When the platform provides a bare Python interpreter (HackerEarth, HackerRank’s default Python 3 mode, some CoCubes rounds), you cannot import it. Knowing the pure-Python methods is therefore necessary even if your daily work uses NumPy.
Choosing the Right Method
The three approaches differ along two practical dimensions: whether you need an external library and how much you want to expose the underlying logic.
| Method | Library needed | Returns | Best for |
|---|---|---|---|
zip(*matrix) | None | List of tuples or lists | Placement coding, quick scripts |
| Nested loop | None | List of lists | Placement interviews (explain the index swap) |
NumPy .T | NumPy | ndarray view | Data science pipelines, large arrays |
For a placement coding round where the goal is a correct, readable submission, zip(*matrix) is the fastest to write and the hardest to get wrong. For a technical interview where the interviewer says “walk me through your implementation,” the nested-loop version lets you narrate the index-swap logic step by step.
For roles at firms that weight algorithmic thinking and data fluency, D.E. Shaw’s recruitment process includes programming rounds where matrix manipulation problems appear alongside graph and dynamic programming questions. In those contexts, being able to explain time and space complexity for the nested-loop approach is as important as producing correct output.
Whichever method you choose, the edge case to handle is an empty matrix. Passing an empty list to zip(*[]) returns an empty iterator, so the list comprehension produces []. Passing an empty list to transpose_nested causes len(matrix[0]) to raise an IndexError. A one-line guard at the top of the function handles it: return early if not matrix.
For broader coding-round preparation, placement preparation resources cover the standard texts and practice platforms that include matrix manipulation as part of their data structure curricula.
Knowing how to manipulate a list-of-lists well enough to transpose it with zip(*matrix) is the same mental model you use when reshaping JSON responses from an LLM API call. If you want to move from matrix exercises to actual model calls in Python, TinkerLLM is where to start at ₹299.
Primary sources
Frequently asked questions
What is the transpose of a matrix in Python?
The transpose swaps rows and columns so that element M[i][j] becomes T[j][i]. Python offers three main approaches: the zip(*matrix) one-liner, a nested loop with pre-allocated array, and NumPy's .T attribute.
Can I transpose a non-square matrix in Python?
Yes. All three methods work on non-square matrices. A 3x4 matrix transposes to a 4x3 matrix regardless of which approach you use. The dimensions simply swap: m rows and n columns become n rows and m columns.
What does zip(*matrix) do for transposing?
The * operator unpacks the matrix into its individual rows as separate arguments to zip(). zip() then groups corresponding elements across rows, producing tuples that represent the columns of the original — which are the rows of the transpose.
Does NumPy .T modify the original matrix?
No, but .T returns a view, not an independent copy. Changes made to the transposed view will affect the original array. Use matrix.T.copy() when you need a fully independent transposed array.
Which transpose method is fastest for large matrices?
NumPy .T is the fastest for large matrices because it is implemented in C and returns a view without copying data. For pure-Python code, zip(*matrix) outperforms the nested-loop approach because Python's built-in zip() is implemented in C.
How does matrix transpose appear in placement coding rounds?
Placement tests at product and analytics companies often include matrix manipulation questions: rotate a matrix, find its transpose, or check if a matrix is symmetric (a matrix is symmetric if it equals its own transpose). The zip(*matrix) method solves all of these in one line.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)