multiple assignments in one line for loop python

Question:

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?

Asked By: amc

||

Answers:

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.

Answered By: Martijn Pieters

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

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

Next time use something other than the "i", like "elem" etc.

Answered By: Václav PastuĊĦek