7

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.

3
  • Probably but I can't think of a practical reason of why you would want to. Commented Mar 1, 2016 at 0:55
  • 1
    @IanAuld you cant see a practical reason for wanting to seperate your x's and y's ? (maybe for plotting in certain libs?) Commented Mar 1, 2016 at 0:57
  • It would probably be more readable and more maintainable to do it separately. There's no need to stick everything on one line. Commented Mar 1, 2016 at 0:59

2 Answers 2

2
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)
Sign up to request clarification or add additional context in comments.

5 Comments

The return types of both of these are tuples not lists
it will give tuples, not lists, but it's the right idea
Sort of. A major difference being mutable != immutable.
maybe /.... usually people don't need mutable for this type of problem ... although its easy enough to make it mutable ...
Just wrap with map(list, ), as in, x, y = map(list, zip(...)) and it will produce lists, not a big deal.
1

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)]))

1 Comment

Note: range only returns list on Py2; on Py3, it's a special range object that would need to be wrapped in the list constructor to make an actual, mutable list. But yes, if the problem is as simple as given, best to avoid the complexity of generating paired values and unpairing them when it's easier to generate unpaired values directly. And if mutability is not needed, using the raw Py3 range would often be better than a mutable list (Py2 xrange isn't quite as good as a drop-in replacement, even if you don't need mutability).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.