Perform Matrix Transpose in Python

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code Examples
2D lists

What you’ll learn

  • Transpose meaning: rows become columns and (A^T)[i][j] = A[j][i].
  • How to build transpose using a second matrix with swapped dimensions.
  • One 2x3 and one 3x3 Python example plus live preview.

Overview

Transpose flips a matrix across its diagonal. A matrix with shape rows x cols becomes cols x rows after transpose.

Two examples

A rectangular 2x3 case and a square 3x3 case.

Live preview

Instantly see original and transposed sample matrices.

Safe approach

Separate output buffer keeps logic simple and error-free.

Prerequisites

List indexing and nested loops in Python.

  • Know matrix representation using nested lists.
  • Comfortable with matrix[row][col] style indexing.

What is the transpose?

Transpose swaps indices: (A^T)[i][j] = A[j][i]. So rows become columns and columns become rows.

If A is m x n, then A^T is n x m.

Shape swap m x n -> n x m
Double transpose (A^T)^T = A

Formal rule

In code, a common implementation is transposed[i][j] = matrix[j][i] where i iterates original columns and j iterates original rows.

Live preview

Uses the same 2x3 sample as code example 1. Click to show original and transposed matrix.

Matches sample values in the first Python program.

Live result
Press "Transpose sample".

Algorithm

Goal: for input matrix rows x cols, fill output matrix cols x rows with swapped indices.

Create output shape

Result dimensions are reversed: cols rows and rows columns.

Copy with swapped indices

Set transposed[i][j] = matrix[j][i] for all valid indices.

Print

Loop through transposed rows and columns to display final output.

📜 Pseudocode

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
1

Transpose a 2x3 matrix (reference)

Rectangular example where shape changes from 2x3 to 3x2.

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

Explanation

The one key assignment is transposed[i][j] = matrix[j][i].

2

Transpose a 3x3 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()

Explanation

For square matrices, in-place transpose is possible, but separate output is easiest for beginners.

Extensions

Square in-place transpose. Swap a[i][j] and a[j][i] for i < j.

Python shortcut. You can also transpose using zip(*matrix) for concise code.

❓ FAQ

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.

🔄 Input / output

To test with your own values, change matrix literals or collect input rows, then run the same transpose logic.

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.

⏱️ Time and space complexity

TaskTimeExtra space
Transpose m x n matrixO(m*n)O(m*n) for output

Summary

  • Rule: (A^T)[i][j] = A[j][i] and shape flips from m x n to n x m.
  • Code: nested loops with swapped indices into output buffer.
  • Identity: transposing twice returns the original matrix.
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.

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