Q:

How do you transpose a matrix using list comprehension in Python?

0

How do you transpose a matrix using list comprehension in Python

In this exercise, you will learn different ways to transpose a matrix using the Python programming language.

The transpose of a matrix is simply a flipped version of the original matrix. We can transpose a matrix by switching its rows and columns, i.e., writing the elements of the rows as columns and writing the elements of a column as rows. For example, the value in the 1st row and 3rd column ends up in the 3rd row and 1st column. In other words, the transpose of B[][] is obtained by changing B[i][j] to B[j][i]. These are different ways to find the transpose of a matrix in Python.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Transpose of a matrix using Nested Loop

In the given Python program, we have used nested loops to iterate through each row and each column. In each iteration, we place the X[i][j] element into result[j][i].

# Matrix
x = [[11,32],[13,20],[30,12]]

result = [[0, 0, 0], [0, 0, 0]]

# Iterate through rows
for i in range(len(x)):
    
   #Iterate through columns
   for j in range(len(x[0])):
      result[j][i] = x[i][j]
      
for r in result:
    print(r)

Output of the above code - 

[11, 13, 30]
[32, 20, 12]

Transpose of a matrix using Nested List Comprehension

Nested List Comprehensions are nothing but a list comprehension within another list comprehension. It is quite similar to a nested loop. Here, we have used this to iterate through each element in the matrix.

# Transpose of a matrix
# using List Comprehension

x = [[19,32],[23,34],[17,19]]

result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))]

for r in result:
   print(r)

Output of the above code - 

[19, 23, 17]
[32, 34, 19]

Transpose of a matrix using zip() function

The Python zip is a holder that holds data inside. Python's zip() function creates an iterator that will aggregate elements from at least two iterables. It returns a zip object, which is an iterator of tuples where the main thing in each passed iterator is matched together, and afterward, the second thing in each passed iterator is combined together, and so on. We can use this method to transpose the matrix. The following example demonstrates this-

# Matrix
x = [[11,32],[13,20],[30,12]]

for row in x: 
    print(row) 
print("\n") 
t_matrix = zip(*x) 
for row in t_matrix: 
    print(row) 

Output of the above code - 

[11, 32]
[13, 20]
[30, 12]


(11, 13, 30)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Exercises, Practice Questions and Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How do you make a simple calculator in Python?... >>
<< Write a program to find the largest of three numbe...