Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unzip a list of tuples into individual lists? [duplicate]

Possible Duplicate:
A Transpose/Unzip Function in Python

I have a list of tuples, where I want to unzip this list into two independent lists. I'm looking for some standardized operation in Python.

>>> l = [(1,2), (3,4), (8,9)]
>>> f_xxx (l)
[ [1, 3, 8], [2, 4, 9] ] 

I'm looking for a succinct and pythonic way to achieve this.

Basically, I'm hunting for inverse operation of zip() function.

like image 275
VaidAbhishek Avatar asked Oct 19 '12 12:10

VaidAbhishek


People also ask

How do you separate a list of tuples?

To split a tuple, just list the variable names separated by commas on the left-hand side of an equals sign, and then a tuple on the right-hand side.

How do I unpack a list of tuples?

If you want to unzip your list of tuples, you use the combination of zip() method and * operator.

How do you unzip a list in Python?

* operator unzips the tuples into independent lists. This is yet another way that can be employed to perform this task of unzipping which is less known but indeed a method to achieve this task. This also uses the * operator to perform the basic unpacking of the list. This function is deprecated in Python >= 3 versions.

How do you duplicate a tuple?

copy. copy() and copy. deepcopy() just copy the reference for an immutable object like a tuple.


1 Answers

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists
like image 151
Martijn Pieters Avatar answered Oct 17 '22 06:10

Martijn Pieters