Suppose I have this code:
JavaScript
x
6
1
def f(x):
2
return 2*x,x*x
3
4
x = range(3)
5
xlist, ylist = [f(value) for value in x]
6
How can I neatly get a result like this?
JavaScript
1
3
1
xlist = [0, 2, 4]
2
ylist = [0, 1, 4]
3
Advertisement
Answer
Note that return 2*x,x
is short for return (2*x,x)
, i.e. a tuple. Your list comprehension thus generates a list of tuples, not a tuple of lists. The nice thing of zip
however is that you can easily use it in reverse with the asterisk:
JavaScript
1
3
1
xlist,ylist = zip(*[f(value) for value in x])
2
# ^ with asterisk
3
Note that xlist
and ylist
will be tuples (since zip
will be unpacked). If you want them to be lists, you can for instance use:
JavaScript
1
2
1
xlist,ylist = map(list, zip(*[f(value) for value in x]))
2
which results in:
JavaScript
1
5
1
>>> xlist
2
[0, 2, 4]
3
>>> ylist
4
[0, 1, 4]
5
Another way to do this is with separate list comprehensions:
JavaScript
1
3
1
xlist = [f(value)[0] for value in x]
2
ylist = [f(value)[1] for value in x]
3
Of course, this repeats the work of f
, which is inelegant and can be inefficient.