I have a function that returns two values, and I would like to use list comprehension to populate two lists. eg:
def f(x):
return 2*x,x*x
x = range(3)
xlist, ylist = [f(value) for value in x]
EDITS from answers below:
xtuple, ytuple = zip(*[f(value) for value in x])
xlist, ylist = map(list,zip(*[f(value) for value in x]))
where the expected return should be:
xlist = [0, 2, 4]
ylist = [0, 1, 4]
my question comes down to:
I am currently getting a list of tuples, while this is reasonable, I will need two independent lists. currently I can have a variable 1 placeholder (tuple) and 3 full understandings. But I am wondering if there is a clean way to do this using a single list.
It is worth noting: in real code, my two returns are correlated, so I can’t just split the function into two.
source
share