3

I have a list of tuples, like this:

loft = [(1, 2), (3, 4), (5, 6)]

I want the result to be like this:

odd = [1, 3, 5]
even = [2, 4, 6]

I can achieve this like this:

odd = [x[0] for x in loft]
even = [x[1] for x in loft]

But I need to do it in one line. I tried this:

odd, even = [x[0], x[1] for x in loft]

But gives me this error:

File "<stdin>", line 1
    odd, even = [x[0], x[1] for x in loft]
                         ^
SyntaxError: invalid syntax

Is it possible to do it in one line?

Amir Shabani
  • 3,857
  • 6
  • 30
  • 67

1 Answers1

6

You can use unpacking with zip:

loft = [(1, 2), (3, 4), (5, 6)]
odd, even = zip(*loft)

Output:

(1, 3, 5)
(2, 4, 6)

If you wish the results to be lists, rather than tuples, you can use map:

loft = [(1, 2), (3, 4), (5, 6)]
odd, even = map(list, zip(*loft))

Output:

[1, 3, 5]
[2, 4, 6]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102