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
Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.
Python3. Method #2: Using zip() and * operator Mostly used method to perform unzip and most Pythonic and recommended as well. This method is generally used to perform this task by programmers all over. * operator unzips the tuples into independent lists.
we can create a list of tuples using list and tuples directly.
Method #1 : Using + operator This is the most Pythonic and recommended method to perform this particular task. In this, we add two tuples and return the concatenated tuple. No previous tuple is changed in this process.
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.
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)
.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With