7

I have a list of tuples as follows: [(12,1),(123,4),(33,4)] and I want it to turn into [12,123,33] and [1,4,4] I was just wondering how I would go about this?

Cheers in advance

Cianan Sims
  • 3,419
  • 1
  • 21
  • 30
miik
  • 663
  • 1
  • 8
  • 23

3 Answers3

21

You could use zip():

zipped = [(12, 1), (123, 4), (33, 4)]
>>> b, c = zip(*zipped)
>>> b 
(12, 123, 33)
>>> c
(1, 4, 4)

Or you could achieve something similar using list comprehensions:

>>> b, c = [e[0] for e in zipped], [e[1] for e in zipped]
>>> b
[12, 123, 33]
>>> c
[1, 4, 4]

Difference being, one gives you a list of tuples (zip), the other a tuple of lists (the two list comprehensions).

In this case zip would probably be the more pythonic way and also faster.

pyrrrat
  • 359
  • 1
  • 4
  • 2
    Not only does this answer work, it's also a good example of how to think in python. – austin Jan 26 '13 at 14:21
  • 1
    -1. The first example is a terrible idea - it only works on sequences, not arbitrary iterables, it's slower, and reinventing the wheel of a builtin, for a more limited case. `zip()` is the only answer that should be considered here. Putting the worst way of doing it first is misleading at best. – Gareth Latty Jan 26 '13 at 14:35
  • @Lattyware You're right, I switched the examples, the more pythonic one should go on top. I think the list comprehensions have their use case though and shouldn't be dismissed. – pyrrrat Jan 26 '13 at 14:45
  • I took the -1 away, but there is literally no use case where the list comprehensions are a better solution here. If you *really* need a list of lists (which is extremely unlikely), [NPE's answer](http://stackoverflow.com/a/14537754/722121) is the best option. – Gareth Latty Jan 26 '13 at 14:48
9

This is a perfect use case for zip():

In [41]: l = [(12,1), (123,4), (33,4)]

In [42]: a, b = map(list, zip(*l))

In [43]: a
Out[43]: [12, 123, 33]

In [44]: b
Out[44]: [1, 4, 4]

If you don't mind a and b being tuples rather than lists, you can remove the map(list, ...) and just keep a, b = zip(*l).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

This would be my go at it.

first_list = []
second_list = []

for tup in list_of_tuples:
    first_list.append(ls[0])
    second_list.append(ls[1])
NlightNFotis
  • 9,559
  • 5
  • 43
  • 66
  • According to my experiment, this solution is even faster than `zip`: https://stackoverflow.com/a/47148258/1911674 – franklsf95 Nov 07 '17 at 00:53