If I have a list like this:
>>> data = [(1,2),(40,2),(9,80)]
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?
If I have a list like this:
>>> data = [(1,2),(40,2),(9,80)]
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?
The unzip operation is:
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 on assignment:
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)
is equivalent to
zip((1,2), (40,2), (9,80))
The two tuples in the result list are built from the first elements of zip()'s arguments and from the second elements of zip()'s arguments.