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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.