Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple lists from comprehension in python

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.

like image 807
yippy1123581321 Avatar asked Mar 01 '16 00:03

yippy1123581321


People also ask

Can list comprehension return two lists?

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.

Can you return a list comprehension Python?

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.

Does list comprehension return a list?

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.


2 Answers

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)
like image 169
Joran Beasley Avatar answered Oct 16 '22 04:10

Joran Beasley


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)]))
like image 29
dawg Avatar answered Oct 16 '22 04:10

dawg