I don't know whether it is anyway possible in Python and that is the reason why I ask it here.
I have a Python function that returns a tuple:
def my_func(i):
return i * 2, 'a' * i
This is just a dumb function that given a number k, it returns k * 2 as is and another string is the letter 'a' concatenated k times.
I want now to form two lists, calling the function with i = 0...9, I want to create one list with all the first values and another one with the rest of them.
What I do with my current knowledge is:
Option 1: Run the same list comprehension two times, that is not very efficient:
first_vals = [my_func(i)[0] for i in range(10)]
second_vals = [my_func(i)[1] for i in range(10)]
Option 2: Avoiding list comprehensions:
first_vals = []
second_vals = []
for i in range(10):
f, s = my_func(i)
first_vals.append(f)
second_vals.append(s)
Option 3: Use list comprehension to get a list of tuples and then two other list comprehension to copy the values. It is better than Option 1, as here my_func() is only called once for each i:
ret = [my_func(i) for i in range(10)]
first_vals = [r[0] for r in ret]
second_vals = [r[1] for r in ret]
Is it possible to somehow use the list comprehension feature in order to return two lists in one command and one iteration, assigning each returned parameter into a different list?
Option 4: Use the inverse of zip:
first_vals, second_vals = zip(*[my_func(i) for i in range(10)])
As Mark Dickinson pointed out in the comment this will lead to tuples for first_vals and second_vals. If you need them to be of type list you can, for example, apply a map:
first_vals, second_vals = map(list, zip(*[my_func(i) for i in range(10)]))
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