1

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?

amc
  • 813
  • 1
  • 15
  • 28

2 Answers2

2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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.