ffledgling
ffledgling

Reputation: 12140

Transpose of a Matrix

I'm trying to find the transpose of a matrix in python without actually using the size of the matrix.

I need to use list comprehensions to do something like [[row[i] for row in test] for i in range(n)] where test is a nxn matrix without actually using n.

Upvotes: 2

Views: 701

Answers (3)

Zubair
Zubair

Reputation: 11

list comprehension can help as written below:

def transpose(matrix):
    return [[row[col] for row in matrix] for col in range(len(matrix[0]))]

Upvotes: 1

unutbu
unutbu

Reputation: 879291

If test is a matrix represented by a list of lists, then

zip(*test)

is the transpose. For example,

In [16]: t = [[1,2,3],[4,5,6]]

In [17]: t
Out[17]: [[1, 2, 3], 
          [4, 5, 6]]

In [18]: zip(*t)
Out[18]: [(1, 4), 
          (2, 5), 
          (3, 6)]

(The output has been formatted to show the result more clearly).

To understand zip(*t) first study how zip works, and then study argument unpacking. It is somewhat of a mind-bender, but once you see how it works, you'll be an expert at both concepts and the effect is quite pleasing.


There is no reason to use list comprehension here, but here is how you could do it anyway:

In [21]: [[row[i] for row in t] for i in range(len(t[1]))]
Out[21]: [[1, 4], [2, 5], [3, 6]]

(len(t[1]) gives the number of columns.)

Upvotes: 5

lbolla
lbolla

Reputation: 5411

You can use a combination of zip and *:

>>> list(zip(*[[1,2,3],[4,5,6]]))
[(1, 4), (2, 5), (3, 6)]

Upvotes: 1

Related Questions