Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transpose a List? [duplicate]

Let's say I have a SINGLE list [[1,2,3],[4,5,6]]

How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]?

Do I have to use the zip function? Is the zip function the easiest way?

def m_transpose(m):
    trans = zip(m)
    return trans
like image 958
user2581724 Avatar asked Dec 18 '25 04:12

user2581724


1 Answers

Using zip and *splat is the easiest way in pure Python.

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

Note that you get tuples inside instead of lists. If you need the lists, use map(list, zip(*l)).

If you're open to using numpy instead of a list of lists, then using the .T attribute is even easier:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]
like image 137
wim Avatar answered Dec 20 '25 16:12

wim