Python program to transpose a matrix

A matrix is a collection of numbers arranged in rows and columns. The matrix transpose can be computed by interchanging its rows into columns or columns into rows.

Here are three different ways of doing Python matrix transpose.

Using Numpy array

import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
transpose = np.transpose(matrix)
print(transpose)

Output

[[1 4 7]
 [2 5 8]
 [3 6 9]]

Here in the above program, we use the NumPy library, which is a powerful tool for working with arrays and matrices in Python. The Numpy module has a transpose function, which is used to transpose a matrix.

Using Python For loop

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = []

for i in range(len(matrix[0])):
    row = []
    for j in range(len(matrix)):
        row.append(matrix[j][i])
    transpose.append(row)

print(transpose)

In the above program we create a matrix with three rows and three columns, then transposes it using a loop. The for loop iterates through each element in the matrix and creates a new row for each column in the original matrix.

Output

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Using python List comprehension

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transpose)

Output

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

In the above program, we create a matrix with three rows and three columns, then transposes it using a nested list comprehension.

Leave a Comment