Perform Matrix Transpose in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2D lists

What You’ll Learn

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.

Definition

Rows ↔ cols

Each entry at (row, col) moves to (col, row).

Shape Flip

m×n → n×m

Output dimensions are the reverse of the input.

Index Rule

T[i][j]=A[j][i]

The one assignment that defines transpose.

Second Buffer

Safe copy

Separate output avoids overwriting values mid-copy.

Live Preview

2×3 sample

See original and transposed matrices in the browser.

Double Flip

(Aᵀ)ᵀ = A

Transposing twice returns the original matrix.

Introduction

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.

Why it matters?

It tests 2D indexing and shape reasoning — a classic warm-up after entrywise matrix operations.

Key Highlights

Swap Indices

Copy with out[i][j] = a[j][i].

Flip Shape

Allocate cols × rows for output.

Safe Buffer

Separate output keeps beginner code clear.

Involution

Two transposes restore A.

In short: create an n × m buffer, then set out[i][j] = a[j][i] for every index.

📝 Problem & Approach

Given matrix A with shape m × n, build A^T with shape n × m by swapping indices.

python
# [[1, 2, 3], [4, 5, 6]]^T = [[1, 4], [2, 5], [3, 6]]
# 2x3 -> 3x2; out[i][j] = a[j][i]

Inputs & Outputs

ItemTypeDescription
matrixlist[list[int]]Input matrix with uniform row lengths.
Return / printmatrix / textTransposed matrix with flipped shape.

Minimal workflow

Pseudocode
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 comparison

MethodIdeaNotes
Second bufferout[i][j] = a[j][i]Interview default — works for any shape
Square in-placeSwap a[i][j] with a[j][i] for i < jOnly when rows == cols
zip(*matrix)Pythonic one-linerFine in apps; show loops in interviews

⚡ Quick Reference

GoalPattern
Copy entrytransposed[i][j] = matrix[j][i]
Output shape[[0]*rows for _ in range(cols)]
Loop orderfor i in range(cols): for j in range(rows)
Rectangular demo2×3 → 3×2
Square in-placeSwap when i < j
Identity check(A^T)^T == A

📋 Buffer vs In-Place vs zip

Same transpose — different implementation styles.

Second buffer
out[i][j] = a[j][i]

This page — clear for any shape

Square in-place
swap a[i][j], a[j][i]

O(1) extra space when n = n

zip shortcut
list(zip(*a))

Concise; tuples unless wrapped

Interview tip
state shape flip

Say m×n → n×m before coding

Context

When This Problem Shows Up

Reach for transpose when rows must become columns.

  1. Interview warm-ups

    Index swapping and shape flip in one short task.

  2. After entrywise ops

    Natural close to the matrix arithmetic chain.

  3. Linear algebra prep

    Needed before products that use AT.

  4. Data reshaping

    Turn row-major tables into column views.

  5. Not entrywise

    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.

🔮 Live Preview

Uses the same 2×3 sample as Example 1. Click to show original and transposed matrix.

Matches sample values in the first Python program.

Live result
Press “Transpose sample”.

Examples Gallery

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.

📚 Getting Started

Second buffer with swapped dimensions — safest beginner pattern.

Example 1 — Transpose a 2×3 Matrix

Rectangular example where shape changes from 2×3 to 3×2.

python
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()

How It Works

The one key assignment is transposed[i][j] = matrix[j][i]. Output is allocated as cols × rows so the shape flip is explicit.

⚡ Square Case

Same dimensions after transpose — still use a buffer for clarity.

Example 2 — Transpose a 3×3 Matrix

Square matrix example where output has the same dimensions.

python
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()

How It Works

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].

⚙️ In-Place (Square Only)

Swap above the diagonal when rows equal columns.

Example 3 — Square In-Place Transpose

Swaps a[i][j] with a[j][i] for i < j — no second matrix.

python
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)

How It Works

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.

🧠 How the Algorithm Builds AT

1

Read shape

rows = len(A), cols = len(A[0]); output will be cols × rows.

Shape
2

Allocate buffer

Create a cols × rows zero matrix (or empty rows).

Buffer
3

Copy swapped

Set out[i][j] = A[j][i] for all valid i, j.

Loops
=

Transpose ready

Rows of A are now columns of AT.

🔎 Worked Walkthrough — 2×3 Sample

Trace how [[1, 2, 3], [4, 5, 6]] becomes a 3×2 matrix.

out[i][j]ReadsValue
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.

Use Cases

Where matrix transpose shows up beyond the interview prompt.

1. Interview Warm-Ups

2D indexing with a shape flip.

Example: write transpose_matrix(A).

2. After Subtraction

Close the matrix arithmetic sequence.

Example: next skill after A − B.

3. Products With Aᵀ

Some formulas need AT before multiplying.

Example: ATA style steps.

4. Table Reshape

Turn row lists into column lists.

Example: pivot a small grid.

5. Space Trade-offs

Buffer vs square in-place discussion.

Example: mention O(mn) output space.

6. Bridge to Arrays

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.

Advantages

Why the second-buffer approach works well in interviews.

  1. 1. One Clear Rule

    out[i][j] = A[j][i] — easy to state and verify.

  2. 2. Works for Any Shape

    Rectangular and square use the same buffer pattern.

  3. 3. Easy Dry-Run

    2×3 sample verifies the flip in seconds.

  4. 4. Room to Extend

    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.

Usage Tips

Small habits that keep transpose solutions interview-ready.

  1. 1. State Shape Flip First

    Say m×n → n×m before writing code.

  2. 2. Allocate cols × rows

    Output width is original row count.

  3. 3. Keep Indices Straight

    Always write out[i][j] = a[j][i], not the reverse.

  4. 4. Guard Empty Input

    Check before reading matrix[0].

  5. 5. State O(m·n)

    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.

Common Pitfalls

Mistakes that commonly break transpose solutions.

  1. 1. Wrong Index Order

    Writing out[i][j] = a[i][j] (no swap).

    → Always use a[j][i] on the right-hand side.

  2. 2. Allocating Wrong Shape

    Creating an m×n buffer instead of n×m.

    → Output rows = original cols.

  3. 3. In-Place on Rectangular

    Trying to reshape without a new buffer.

    → Use a second matrix when m ≠ n.

  4. 4. Empty or Ragged Input

    Accessing matrix[0] on [] or uneven rows.

    → Guard empties; require uniform row lengths.

  5. 5. Shared Row Initialization

    [[0]*rows]*cols shares row lists.

    → Build each row separately.

Edge Cases

Keep shapes and indexing consistent.

Empty

Empty matrix input

Guard against empty list before accessing matrix[0].

Ragged

Unequal row lengths

Transpose assumes each row has same number of columns.

1×n

Single row

Becomes an n×1 column matrix.

n×1

Single column

Becomes a 1×n row matrix.

1×1

Single cell

Transpose equals itself.

Square

In-place option

Only when rows == cols; otherwise use a buffer.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Definition. (AT)ij = Aji.
  • Involution. (AT)T = A.
  • Products. (AB)T = BTAT when AB exists.
  • Symmetric. A is symmetric when AT = A (square only).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Dry-run 2×3

  • Reproduce Example 1 by hand
  • Expect [[1, 4], [2, 5], [3, 6]]

2. Double transpose

  • Transpose Example 1 twice
  • Confirm you get the original back

3. Square in-place

  • Implement Example 3 swaps
  • Only loop j > i

4. Guard empties

  • Return [] for empty input
  • Reject ragged rows

Notes

  • Rule: (A^T)[i][j] = A[j][i] and shape flips from m×n to n×m.
  • Code: nested loops with swapped indices into an output buffer.
  • Identity: transposing twice returns the original matrix.
  • Square in-place swaps are optional; zip(*matrix) is a concise Python shortcut.

Quick Takeaway: allocate n×m, then out[i][j] = A[j][i]; (AT)T = A.

⏱️ Time and Space Complexity

TaskTimeExtra space
Transpose m × n with bufferO(m*n)O(m*n) for output
Square in-placeO(n^2)O(1) beyond input
Shape / ragged checksO(m)O(1)

Each element is visited once; the buffer approach stores a full copy of the flipped matrix.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • State m×n → n×m first
  • Allocate a cols×rows buffer
  • Use out[i][j] = a[j][i]
  • Guard empty / ragged inputs
  • State O(m*n) time and space

❌ Don’t

  • Forget to swap indices
  • Allocate the wrong output shape
  • In-place transpose non-square matrices
  • Skip empty-list checks
  • Use shared-row list init

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix transpose

Flip matrices the interview-friendly way.

5
Core concepts
= 02

Shape

m×n → n×m

Constraint
2 03

Buffer

Safe second matrix

Pattern
04

Twice

(Aᵀ)ᵀ = A

Property
O 05

Cost

O(m·n)

Analysis

❓ Frequently Asked Questions

Transpose swaps row and column positions: each entry at (row, col) moves to (col, row).
It becomes 3 rows and 2 columns. In general, m x n becomes n x m.
The transposed entry at [i][j] equals original [j][i], written as (A^T)[i][j] = A[j][i].
For non-square matrices, shape changes so you usually need a separate buffer. In-place transpose is practical mainly for square matrices.
It avoids overwriting values you still need while copying with swapped indices.
Each element is visited once, so time is O(m*n) for an m x n matrix.
Transposing twice returns the original matrix: (A^T)^T = A.
It is a concise Python shortcut. Interviews usually want nested loops first so you show indexing clearly.

Did you Know? 🔊

The 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.

Continue to Array Maximum

Learn how to scan a list once and track the largest value.

Array maximum tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful