scroll_lock
scroll_lock

Reputation: 143

Assign two variables from list of tuples in one iteration

I have a function foo() that returns a tuple. Let's say ('a', 1) I have an iterable a that I want to iterate over and pass every item to that function. At the end I need two lists - r1 and r2 where r1 consists of all the first items in the tuples returned from the function. The second list r2 - the result of all the second items in these tuples.

r1 = ['a', 'b', 'c']
r2 = [1, 2, 3]

I don't like this approach too much:

result = [foo(i) for i in a]
r1 = [i[0] for i in result]
r2 = [i[1] for i in result]

Upvotes: 2

Views: 4106

Answers (3)

Volatility
Volatility

Reputation: 32300

You can use the zip function for this.

>>> result = [('a', 1), ('b', 2), ('c', 3)]
>>> r1, r2 = zip(*result)
>>> r1
('a', 'b', 'c')
>>> r2
(1, 2, 3)

zip(*result) unpacks each list in result and passes them as separate arguments into the zip function. It essentially transposes the list. It produces a list of two tuples, which then are assigned to r1 and r2.

Upvotes: 9

WeeniehuahuaXD
WeeniehuahuaXD

Reputation: 852

The zip function will do you just fine. Here is a helpful post here that is related directly to that function

understanding zip function

Upvotes: 0

James
James

Reputation: 2795

Just use zip()!

result = [foo(i) for i in a]
r1, r2 = zip(*result)

Upvotes: 2

Related Questions