Python Program To Find Transpose of a Matrix


Gaming Laptop Series

The transpose of a matrix is obtained by interchanging its rows into columns and columns into rows. It is denoted by the letter T in the subscript of the given matrix.

For example –

matrix a

The transpose of the matrix A is :

transpose of matrix a

In this article, I will show you the Python code to find the transpose of a matrix.

Python program to find the transpose of a matrix

We will use the given methods to find the transpose of a matrix in Python.

  • Using nested for loop
  • Using list comprehension

Using nested for loop

In this, we will use nested loops to iterate determine the transpose of the given matrix.

# Python program to find transpose a matrix using a nested for loop

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

Transpose_of_matrix = [[0,0,0],
                      [0,0,0],
                      [0,0,0]]

# Iterate through matrix rows
for i in range(len(matrix)):
   # Iterate through matrix columns
   for j in range(len(matrix[0])):
       Transpose_of_matrix[j][i] = matrix[i][j]

for r in Transpose_of_matrix:
   print(r)

Save this file with the .py extension and execute. You will see the given output in your terminal.

transpose of a matrix

Using list comprehension

Another way to find the transpose of a matrix is by using list comprehension. This uses a reduced number of lines in code and performs the same task.

#Python program to find the transpose of a matrix using list comprehension

matrix = [[6,0],
         [1,5],
         [8,3]]

# Using list comprehension
transpose_of_matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

for r in transpose_of_matrix:
   print(r)

When you execute this code you will see the transpose of the given matrix.

The output is :

output

Conclusion

So I hope now you are able to find the transpose of a matrix in Python. Now for any query, you can write us in the comments below.

Leave a Comment

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