# Python Program to Transpose a Matrix

By | October 3, 2021 There are several operations that we can perform on matrices. The transpose of a matrix is one such operation. The resulting matrix has interchanged rows and columns of the original one. Here in this article, we have provided python source code for transposing a matrix.

## Matrix and Transpose

A matrix is a 2-dimensional array, which is formed by using columns and rows. Matrices are very useful in scientific computation. In Python, to represent a matrix, we use a list of lists. To transpose a matrix, we switch its row values with the column values.

For instance,

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

is a matrix, and for transposing it, we switch its row values with its column values i.e.:

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

## Prerequisite Topics to Create this Program

• Python Input/output
• Lists in Python
• Python Loop
• Python List comprehension

## Steps for Transposing a Matrix

• Ask the user to enter the number of rows and columns for a matrix.
• Then using the list comprehension and input() function, ask the user to enter the elements in the matrix.
• Create a result matrix, whose dimensions are the invert of the user-entered matrix dimensions. For instance, if the matrix has 2 rows and 3 columns then the resulting matrix (transpose) should have 3 rows and 2 columns.
• Using the nested for loop, we will change the row values with the column values then store them into the resulting matrix.

## Python Program to Transpose a Matrix

Code:

```rows = int(input("Enter the Number of rows : " ))
column = int(input("Enter the Number of Columns: "))

print("Enter the elements of Matrix:")
matrix= [[int(input()) for i in range(column)] for i in range(rows)]
for n in matrix:
print(n)

#result matrix of column*row  dimension

result =[[0 for i in range(rows)] for j in range(column)]

#transpose the matrix
for r in range(rows):

for c in range(column):
#here we are grabbing the row data of matrix and putting it in the column on the result
result[c][r] = matrix[r][c]

print("Transpose matrix is: ")
for r in result:
print(r)
```

Output 1:

```Enter the Number of rows : 3
Enter the Number of Columns: 3
Enter the elements of Matrix:
1
2
3
4
5
6
7
8
9
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transpose matrix is:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]```

Output 2

```Enter the Number of rows : 2
Enter the Number of Columns: 4
Enter the elements of Matrix:
1
2
3
4
5
6
7
8