Editor

Python Program to Transpose a Matrix

Beginner · Matrices

The transpose of a matrix is made by turning its rows into columns, so the item in row i, column j moves to row j, column i. A 2 x 3 matrix becomes a 3 x 2 matrix. This program builds the transpose with nested loops.

Program

transpose_matrix.py
matrix = [[1, 2, 3],
[4, 5, 6]]
rows = len(matrix)
cols = len(matrix[0])
# Each column of the original becomes a row of the transpose
transpose = []
for j in range(cols):
new_row = []
for i in range(rows):
new_row.append(matrix[i][j])
transpose.append(new_row)
print("Original matrix:")
for row in matrix:
print(row)
print("Transpose:")
for row in transpose:
print(row)
Output
Original matrix:
[1, 2, 3]
[4, 5, 6]
Transpose:
[1, 4]
[2, 5]
[3, 6]

How it works

  1. The matrix is a list of rows: len(matrix) is the number of rows and len(matrix[0]) the number of columns.
  2. The outer loop goes through the columns, because each column of the original becomes a row of the transpose.
  3. The inner loop collects matrix[i][j] from every row into new_row.
  4. Each finished new_row is added to transpose, which is printed row by row.

Other ways to write it

Using zip()

Using zip()
matrix = [[1, 2, 3],
[4, 5, 6]]
transpose = [list(row) for row in zip(*matrix)]
print("Transpose:")
for row in transpose:
print(row)
Output
Transpose:
[1, 4]
[2, 5]
[3, 6]

zip(*matrix) passes each row to zip(), which groups the first items, then the second items, and so on, which are exactly the columns.

Using a nested list comprehension

Using a nested list comprehension
matrix = [[1, 2, 3],
[4, 5, 6]]
transpose = [[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))]
print("Transpose:")
for row in transpose:
print(row)
Output
Transpose:
[1, 4]
[2, 5]
[3, 6]

This is the nested loop version squeezed into one line: the outer part loops over columns, the inner part over rows.

Try it yourself

Check whether a square matrix is symmetric, meaning it equals its own transpose, using [[1, 2], [2, 1]] as an example.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises