30

I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the height of the matrix is 2 and the width is 3):

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

To be transposed the jth item in the ith index should become the ith item in the jth index. Here's how the above sample would look transposed:

>>> transpose([[1, 2, 3],
               [4, 5, 6]])
[[1, 4],
[2, 5],
[3, 6]]
>>> transpose([[1, 2],
               [3, 4]])
[[1, 3],
[2, 4]]

How can I do this?

1

3 Answers 3

110

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Sign up to request clarification or add additional context in comments.

2 Comments

In Python 3, map returns an iterator, so to get a list from the last solution you need list(map(list, zip(*lis))) or [*map(list, zip(*lis))].
Can you explain more on how the * works in zip(*lis)
28

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

2 Comments

Your answer is not correct because of the given skeleton function. This answer must be done using list comprehension. The answer below is correct. Good information though.
Not only you're importing a huge library to do something that can be achieved with one line of pure python, your answer is also technically wrong because the output is not a list of list as shown in the question, but a numpy array. So the answer is longer and slower, because you have to convert to a numpy array, transpose, and convert back.
13

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

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

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

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

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.