Reputation: 663
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
Upvotes: 7
Views: 5120
Reputation: 359
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.
Upvotes: 21
Reputation: 500357
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)
.
Upvotes: 9
Reputation: 9805
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])
Upvotes: 1