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?