Search code examples
pythonlistlist-comprehensionunpack

unpick a list of lists in Python


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...


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)