Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a list of tuples into two lists

Tags:

python

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

like image 621
miik Avatar asked Jan 26 '13 14:01

miik


People also ask

How do I make a list from a list of tuples?

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.

How do I unpack a list of tuples in Python?

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.

Can you make a list of tuples?

we can create a list of tuples using list and tuples directly.

How do you merge two tuples in Python?

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.


3 Answers

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.

like image 63
pyrrrat Avatar answered Oct 19 '22 12:10

pyrrrat


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).

like image 42
NPE Avatar answered Oct 19 '22 11:10

NPE


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])
like image 29
NlightNFotis Avatar answered Oct 19 '22 12:10

NlightNFotis