Question

i have a list of 3 lists in Python

mylist = [[1, 2, 3], [10, 20, 30], [100, 200, 300]]

and i unpack using 3 lines of code

first= [m[0] for m in mylist]
second = [m[1] for m in mylist]
third = [m[2] for m in mylist]

I wish to find an efficient one line code for the same...

Was it helpful?

Solution

You can use zip:

first,second,third = zip(*[[1, 2, 3], [10, 20, 30], [100, 200, 300]])

In [10]: first
Out[10]: (1, 10, 100)

In [11]: second
Out[11]: (2, 20, 200)

In [12]: third
Out[12]: (3, 30, 300)

OTHER TIPS

Are you quite sure you shouldn't be using numpy for this?

>>> import numpy
>>> myarray = numpy.array(mylist)
>>> myarray
array([[  1,   2,   3],
       [ 10,  20,  30],
       [100, 200, 300]])

just access them directly:

>>> myarray[...,0]
array([  1,  10, 100])
>>> myarray[...,1]
array([  2,  20, 200])
>>> myarray[...,2]
array([  3,  30, 300])

or give them names if you like:

>>> a, b, c = myarray
>>> a
array([1, 2, 3])
>>> b
array([10, 20, 30])
>>> c
array([100, 200, 300])
>>> d, e, f = myarray.transpose()
>>> d
array([  1,  10, 100])
>>> e
array([  2,  20, 200])
>>> f
array([  3,  30, 300])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top