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]
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.
Just use zip()!
result = [foo(i) for i in a]
r1, r2 = zip(*result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With