Extract array from list in python

If I have a list like this:

>>> data = [(1,2),(40,2),(9,80)]

how can i extract two lists [1,40,9] and [2,2,80]? Sure, I can iterate and extract numbers myself, but I think there is a better way?

+4
source share
3 answers

Matching lists to save the day:

 first = [x for (x,y) in data] second = [y for (x,y) in data] 
+14
source

Unpacking operation:

 In [1]: data = [(1,2),(40,2),(9,80)] In [2]: zip(*data) Out[2]: [(1, 40, 9), (2, 2, 80)] 

Edit: you can decompose the resulting list when assigning:

 In [3]: first_elements, second_elements = zip(*data) 

And if you really need lists as results:

 In [4]: first_elements, second_elements = map(list, zip(*data)) 

To better understand why this works:

 zip(*data) 

equivalently

 zip((1,2), (40,2), (9,80)) 

Two tuples in the list of results are constructed from the first elements of the zip () arguments and from the second elements of the zip () arguments.

+26
source

There is also

 In [1]: data = [(1,2),(40,2),(9,80)] In [2]: x=map(None, *data) Out[2]: [(1, 40, 9), (2, 2, 80)] In [3]: map(None,*x) Out[3]: [(1, 2), (40, 2), (9, 80)] 
+5
source

All Articles