1

I have a list of lists that looks like this;

[[4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0]]

Which is the most efficient way to get 3 lists from the above list based on the position of the element?

Result:

[4,0,0,1,2]
[0,0,1,1,0]
[1,1,2,0,0]
richie
  • 17,568
  • 19
  • 51
  • 70

1 Answers1

9

You can use zip and a list comprehension:

>>> lst = [[4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0]]
>>> [list(x) for x in zip(*lst)]
[[4, 0, 0, 1, 2], [0, 0, 1, 1, 0], [1, 1, 2, 0, 0]]
>>>

Placing * before lst unpacks the list into arguments for the zip function. In this case:

zip(*lst)

is equivalent to writing:

zip([4, 0, 1], [0, 0, 1], [0, 1, 2], [1, 1, 0], [2, 0, 0])

zip then zips these lists together by returning an iterator of tuples where the n-th tuple contains the n-th item from each of the lists. In this case, it returns:1

>>> list(zip(*lst))
[(4, 0, 0, 1, 2), (0, 0, 1, 1, 0), (1, 1, 2, 0, 0)]
>>>

Finally, the list comprehension converts these tuples into lists and collects them into a new list.


1You need to call list() on zip(*lst) to view its items because zip returns an iterator in Python 3.x.