Program to transpose a Matrix in Python

Program to transpose a Matrix in Python. This program contains matrices assignment, for loop and print statement. This program is for beginners, class 11,12 and B Tech computer science students.

Program to transpose a Matrix in Python

Source code :

i=0
# Define a matrix A  
A = [[15, 64, 35],  
         [2, 14,96],  
         [54, 17,99],  
         [82, 12, 83]]  
# Define an empty matrix of reverse order  
transResult = [[0, 0, 0, 0],    
                             [0, 0, 0, 0],  
                             [0, 0, 0, 0]]  
# Use nested for loop on matrix A  
for a in range(len(A)):    
   for b in range(len(A[0])):    
          transResult[b][a] = A[a][b] # store transpose result on empty matrix          
# Printing result in the output  
print("The transpose of matrix A is: ")  
for res in transResult:    
   print(res)
#print(i) 

[[15,2,54,82],
[64,14,96]
[35,96,99,83]]

Source code explanation:

Step 1:Define a matrix A
A = [[15, 64, 35],
[2, 14,96],
[54, 17,99],
[82, 12, 83]]
Step 2: Define an empty matrix of reverse order
transResult = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
step 3: Use nested for loop on matrix A
for a in range(len(A)):
for b in range(len(A[0])):
transResult[b][a] = A[a][b] # store transpose result on empty matrix
step 4: Printing result in the output
print(“The transpose of matrix A is: “)
for res in transResult:
print(res)

Output :

The transpose of matrix A is: 
[[15,2,54,82],
[64,14,96]
[35,96,99,83]]

Output Explanation:

A was this

A = [[15, 64, 35],  
         [2, 14,96],  
         [54, 17,99],  
         [82, 12, 83]]

so the transpose after changing column and row A[i][j] = At[j][i].

The transpose of matrix A is: 
[[15,2,54,82],
[64,14,96]
[35,96,99,83]]

Which is correct.

Conclusion:

The program is running fine.

Thank you, You are free for reading , learning and copying the source code of Program to transpose a Matrix in Python . This program contains matrices assignment, for loop and print statement. This program is for beginners, class 11,12 and B Tech computer science students. For more program like this , practical file for 11,12 class and B Tech projects click the links below:
/category/python-programs/
Computer Science with Python Practical Book Solutions Class 11 Term -2 – CS Study
Computer Science Practical file for class 12 Term-2 – CS Study
Python Projects for Class 12 with Source Code (Mysql Connectivity) – CS Study

Leave a Comment

Your email address will not be published.