Is there any way in Python to return multiple lists from a comprehension?
I want to do something to the effect of:
x,y = [i,(-1*j) for (i,j) in enumerate(range(10))]
# x = [0 .. 9]
# y = [0 .. -9]
that's a dumb example, but I'm just wondering if it's possible.
The question was: 'is it possible to return two lists from a list comprehension? '. I answer that it is possible, but in my opinion is better to iterate with a loop and collect the results in two separate lists.
return is a statement. List comprehensions cannot contain statements, only expressions. In fact, that's true for all expressions in Python: they can only contain other expressions. So, no, you can't put a return inside a list comprehension.
List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
x,y =zip(* [(i,(-1*j)) for (i,j) in enumerate(range(10))] )
you just unzip the list
xy = [(1,2),(3,4),(5,6)]
x,y = zip(*xy)
# x = (1,3,5)
# y = (2,4,6)
You can skip the list comprehension:
>>> x,y=range(0,10), range(0,-10,-1)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
Or you could do:
>>> x,y=map(list, zip(*[(e,-e) for e 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