List of tuples in two lists

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 just I wonder how I would do it?

Greetings in advance

+6
source share
3 answers

You can 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 a list of concepts :

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

The difference is that you get a list of tuples ( zip ), and the other is a list of lists (two lists).

In this case, the zip is likely to be more Putin and faster.

+17
source

This is the 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 that a and b are tuples, not lists, you can remove map(list, ...) and just save a, b = zip(*l) .

+8
source

This will be my transition.

 first_list = [] second_list = [] for tup in list_of_tuples: first_list.append(ls[0]) second_list.append(ls[1]) 
+1
source

All Articles