Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign two variables from list of tuples in one iteration

Tags:

python

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]
like image 839
scroll_lock Avatar asked Dec 04 '25 10:12

scroll_lock


2 Answers

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.

like image 120
Volatility Avatar answered Dec 08 '25 08:12

Volatility


Just use zip()!

result = [foo(i) for i in a]
r1, r2 = zip(*result)
like image 23
James Avatar answered Dec 08 '25 08:12

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!