1

I have a list of tuples that looks like this:

x = [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

What is the most pythonic and efficient way to convert into a list of 2 lists where each list respectively has all values of a specific index? Like so:

y = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

Is it possible to do this without a loop?

mic
  • 4,300
  • 1
  • 19
  • 25
  • with pure python, I'd assume you would only achieve this via list comprehension, which is also looping. importing `numpy as np` you couls just do `np.array(x)` (which of course loops internally, too, but hopefully in the fastest way.) – SpghttCd Jun 06 '18 at 05:46
  • numpy is also looping @SpghttCd – Reblochon Masque Jun 06 '18 at 05:46

2 Answers2

3

Here you go without a loop (at least informally)

[[ele[0] for ele in x]] + [[ele[1] for ele in x]]

You have to loop over the elements. There's no other way in python or in any other langauge.

ravi
  • 10,994
  • 1
  • 18
  • 36
3

Look ma, no loops.

>>> list(map(list, zip(*x)))
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • @IljaEverilä yeah thanks. Just wanted to answer since the other answer was so obviously wrong – cs95 Jun 06 '18 at 05:49