Transpose a matrix in Python?


Transpose a matrix means we’re turning its columns into its rows. Let’s understand it by an example what if looks like after the transpose.

Let’s say you have original matrix something like -

x = [[1,2][3,4][5,6]]

In above matrix “x” we have two columns, containing 1, 3, 5 and 2, 4, 6.

So when we transpose above matrix “x”, the columns becomes the rows. So the transposed version of the matrix above would look something like -

x1 = [[1, 3, 5][2, 4, 6]]

So the we have another matrix ‘x1’, which is organized differently with different values in different places.

Below are couple of ways to accomplish this in python -

Method 1 - Matrix transpose using Nested Loop -

#Original Matrix
= [[1,2],[3,4],[5,6]]
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)

Result

[1, 3, 5]
[2, 4, 6]

Method 2 - Matrix transpose using Nested List Comprehension.

#Original Matrix
= [[1,2],[3,4],[5,6]]
result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))]
for r in Result
   print(r)

Result

[1, 3, 5]
[2, 4, 6]

List comprehension allows us to write concise codes and should be used frequently in python.

Method 3 - Matrix Transpose using Zip

#Original Matrix
= [[1,2],[3,4],[5,6]]
result = map(list, zip(*x))
for r in Result
   print(r)

Result

[1, 3, 5]
[2, 4, 6]

Method 4 - Matrix transpose using numpy library Numpy library is an array-processing package built to efficiently manipulate large multi-dimensional array.

import numpy
#Original Matrix
= [[1,2],[3,4],[5,6]]
print(numpy.transpose(x))

Result

[[1 3 5]
[2 4 6]]

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements