pythonfor-loopmultiple-assignment

multiple assignments in one line for loop python


I would like a one line way of assigning two variables to two different values in a for loop.

I have a list of list of values

list_values = [[1, 2, 3], [4, 5, 6]]

I have tried to do this, and it works but is not pythony:

first = [i[0] for i in list_values]
second = [i[1] for i in list_values]

Which makes:

first = [1, 4]
second = [2, 5]

I want to write something like:

first, second = [i[0]; i[1] for i in list_values]

Is something like this possible?


Solution

  • You could use the zip() function instead:

    first, second = zip(*list_values)[:2]
    

    or the Python 3 equivalent:

    from itertools import islice
    
    first, second = islice(zip(*list_values), 2)
    

    zip() pairs up elements from the input lists into a sequence of new tuples; you only need the first two, so you slice the result.