Definition
Rows ↔ cols
Each entry at (row, col) moves to (col, row).
Matrix transpose flips rows into columns: (A^T)[i][j] = A[j][i], so an m × n matrix becomes n × m. This tutorial covers the rule, a second-buffer approach, a live preview, worked Python examples, edge cases, and complexity.
Rows ↔ cols
Each entry at (row, col) moves to (col, row).
m×n → n×m
Output dimensions are the reverse of the input.
T[i][j]=A[j][i]
The one assignment that defines transpose.
Safe copy
Separate output avoids overwriting values mid-copy.
2×3 sample
See original and transposed matrices in the browser.
(Aᵀ)ᵀ = A
Transposing twice returns the original matrix.
Matrix transpose flips a matrix across its diagonal: rows become columns. If A is m × n, then AT is n × m, with (A^T)[i][j] = A[j][i].
Beginners usually build a second matrix of swapped shape. In-place transpose is practical mainly for square matrices; rectangular inputs change dimensions.
It tests 2D indexing and shape reasoning — a classic warm-up after entrywise matrix operations.
Copy with out[i][j] = a[j][i].
Allocate cols × rows for output.
Separate output keeps beginner code clear.
Two transposes restore A.
In short: create an n × m buffer, then set out[i][j] = a[j][i] for every index.
Given matrix A with shape m × n, build A^T with shape n × m by swapping indices.
# [[1, 2, 3], [4, 5, 6]]^T = [[1, 4], [2, 5], [3, 6]]
# 2x3 -> 3x2; out[i][j] = a[j][i] | Item | Type | Description |
|---|---|---|
matrix | list[list[int]] | Input matrix with uniform row lengths. |
| Return / print | matrix / text | Transposed matrix with flipped shape. |
function transpose(matrix, rows, cols):
out <- matrix of shape cols x rows
for i from 0 to cols - 1:
for j from 0 to rows - 1:
out[i][j] <- matrix[j][i]
return out | Method | Idea | Notes |
|---|---|---|
| Second buffer | out[i][j] = a[j][i] | Interview default — works for any shape |
| Square in-place | Swap a[i][j] with a[j][i] for i < j | Only when rows == cols |
zip(*matrix) | Pythonic one-liner | Fine in apps; show loops in interviews |
| Goal | Pattern |
|---|---|
| Copy entry | transposed[i][j] = matrix[j][i] |
| Output shape | [[0]*rows for _ in range(cols)] |
| Loop order | for i in range(cols): for j in range(rows) |
| Rectangular demo | 2×3 → 3×2 |
| Square in-place | Swap when i < j |
| Identity check | (A^T)^T == A |
Same transpose — different implementation styles.
out[i][j] = a[j][i]This page — clear for any shape
swap a[i][j], a[j][i]O(1) extra space when n = n
list(zip(*a))Concise; tuples unless wrapped
state shape flipSay m×n → n×m before coding
Reach for transpose when rows must become columns.
Index swapping and shape flip in one short task.
Natural close to the matrix arithmetic chain.
Needed before products that use AT.
Turn row-major tables into column views.
Clarify: transpose rearranges positions, it does not subtract or divide cells.
Key benefit: one short problem that locks in indexing, shape flip, and why a second buffer is safer for beginners.
Uses the same 2×3 sample as Example 1. Click to show original and transposed matrix.
Three complete Python programs — rectangular 2×3, square 3×3 with a buffer, and square in-place swap. Click View Output to reveal sample console results.
Second buffer with swapped dimensions — safest beginner pattern.
Rectangular example where shape changes from 2×3 to 3×2.
def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:
rows = len(matrix)
cols = len(matrix[0])
transposed = [[0 for _ in range(rows)] for _ in range(cols)]
for i in range(cols):
for j in range(rows):
transposed[i][j] = matrix[j][i]
return transposed
def print_matrix(title: str, m: list[list[int]]) -> None:
print(title)
for row in m:
print("\t".join(str(x) for x in row))
def main() -> None:
matrix = [
[1, 2, 3],
[4, 5, 6],
]
transposed = transpose_matrix(matrix)
print_matrix("Original (2 x 3):", matrix)
print()
print_matrix("Transposed Matrix (3 x 2):", transposed)
if __name__ == "__main__":
main() The one key assignment is transposed[i][j] = matrix[j][i]. Output is allocated as cols × rows so the shape flip is explicit.
Same dimensions after transpose — still use a buffer for clarity.
Square matrix example where output has the same dimensions.
N = 3
def transpose_square(a: list[list[int]]) -> list[list[int]]:
out = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
out[i][j] = a[j][i]
return out
def print_matrix(title: str, m: list[list[int]]) -> None:
print(title)
for row in m:
print(*row)
def main() -> None:
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
t = transpose_square(a)
print_matrix("A", a)
print()
print_matrix("A^T", t)
if __name__ == "__main__":
main() For square matrices, in-place transpose is possible, but separate output is easiest for beginners. First column of A becomes first row of AT: [1, 4, 7].
Swap above the diagonal when rows equal columns.
Swaps a[i][j] with a[j][i] for i < j — no second matrix.
def transpose_inplace(a: list[list[int]]) -> None:
n = len(a)
for i in range(n):
for j in range(i + 1, n):
a[i][j], a[j][i] = a[j][i], a[i][j]
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print("Before:")
for row in a:
print(*row)
transpose_inplace(a)
print("\nAfter (in-place A^T):")
for row in a:
print(*row) Loop only the upper triangle (j > i) so each off-diagonal pair is swapped once. Diagonal cells stay put. Do not use this for non-square matrices — shape must stay the same.
rows = len(A), cols = len(A[0]); output will be cols × rows.
Create a cols × rows zero matrix (or empty rows).
Set out[i][j] = A[j][i] for all valid i, j.
Rows of A are now columns of AT.
Trace how [[1, 2, 3], [4, 5, 6]] becomes a 3×2 matrix.
| out[i][j] | Reads | Value |
|---|---|---|
out[0][0] | A[0][0] | 1 |
out[0][1] | A[1][0] | 4 |
out[1][0] | A[0][1] | 2 |
out[2][1] | A[1][2] | 6 |
Full result: [[1, 4], [2, 5], [3, 6]] — matching Example 1.
Where matrix transpose shows up beyond the interview prompt.
2D indexing with a shape flip.
Example: write transpose_matrix(A).
Close the matrix arithmetic sequence.
Example: next skill after A − B.
Some formulas need AT before multiplying.
Example: ATA style steps.
Turn row lists into column lists.
Example: pivot a small grid.
Buffer vs square in-place discussion.
Example: mention O(mn) output space.
Next page moves to 1D array max.
Example: continue the interview track.
Pro Tip: open with “m×n becomes n×m, out[i][j] = A[j][i]” before writing loops.
Why the second-buffer approach works well in interviews.
out[i][j] = A[j][i] — easy to state and verify.
Rectangular and square use the same buffer pattern.
2×3 sample verifies the flip in seconds.
Natural follow-up: square in-place or zip(*A).
Pro Tip: lead with loops and a buffer; mention zip(*matrix) only as a production aside.
Small habits that keep transpose solutions interview-ready.
Say m×n → n×m before writing code.
Output width is original row count.
Always write out[i][j] = a[j][i], not the reverse.
Check before reading matrix[0].
One visit per cell; output needs O(mn) space.
Pro Tip: dry-run first column → first row: [1, 4] from the 2×3 sample — if that matches, indexing is correct.
Mistakes that commonly break transpose solutions.
Writing out[i][j] = a[i][j] (no swap).
→ Always use a[j][i] on the right-hand side.
Creating an m×n buffer instead of n×m.
→ Output rows = original cols.
Trying to reshape without a new buffer.
→ Use a second matrix when m ≠ n.
Accessing matrix[0] on [] or uneven rows.
→ Guard empties; require uniform row lengths.
[[0]*rows]*cols shares row lists.
→ Build each row separately.
Keep shapes and indexing consistent.
Guard against empty list before accessing matrix[0].
Transpose assumes each row has same number of columns.
Becomes an n×1 column matrix.
Becomes a 1×n row matrix.
Transpose equals itself.
Only when rows == cols; otherwise use a buffer.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
j > i(A^T)[i][j] = A[j][i] and shape flips from m×n to n×m.zip(*matrix) is a concise Python shortcut.Quick Takeaway: allocate n×m, then out[i][j] = A[j][i]; (AT)T = A.
| Task | Time | Extra space |
|---|---|---|
Transpose m × n with buffer | O(m*n) | O(m*n) for output |
| Square in-place | O(n^2) | O(1) beyond input |
| Shape / ragged checks | O(m) | O(1) |
Each element is visited once; the buffer approach stores a full copy of the flipped matrix.
Matrix transpose flips rows into columns with (A^T)[i][j] = A[j][i], turning m×n into n×m. Use a second buffer for clarity; reserve in-place swaps for square matrices.
Practice the three examples above, then continue to finding the maximum value in an array.
Shape flip first, then out[i][j] = A[j][i] with nested loops.
Flip matrices the interview-friendly way.
T[i][j]=A[j][i]
Definitionm×n → n×m
ConstraintSafe second matrix
Pattern(Aᵀ)ᵀ = A
PropertyO(m·n)
AnalysisThe transpose flips a matrix across its diagonal: rows become columns. If A is m x n, then AT is n x m, and (AT)T = A.
Learn how to scan a list once and track the largest value.
8 people found this page helpful