Program to compute transpose of a matrix using Python


In this section of programming, we are going to compute the transpose of a matrix.

Program to compute transpose of a matrix


import numpy as nump
X = [[6, 8, 3], [2, 1, 10], [4, 4, 7]]
# Using numpy
result1 = nump.transpose(X)
print("Transpose of matrix using matrix numpy transpose:")

# Using zip()
result2 = zip(*X)
print("Transpose of matrix using zip():")
for k in result2:

# Using list comprehension
result3 = [[X[j][i] for j in range(len(X))] for i in  range(len(X[0]))]
print("Transpose of matrix using list comprehension:")
for l in result3:


Program to compute transpose of a matrix Output


In the above code, we have created a matrix X with size 3 x 3 . To find the transpose of matrix, python numpy package provides an in-built method “transpose” to compute the transpose of multi-dimensional matrix (we can also write “<matrix-name>.T” instead of numpy.transpose(<matrix-name>) in line 5).

Similarly, the nested list comprehension traverse over each element in column major order(column major and row major are methods to store multi-dimensional arrays in a linear manner).

The third way we used to compute the matrix is using zip(). Firstly, we unzip(by using *) the matrix and then zipped it to get the transpose.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.