## A Transpose/Unzip Function in Python (inverse of zip)

Question!

I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.

For example:

``````original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
``````

Is there a builtin function that does that?

By : Cristian

``````>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
``````

Gives a tuple of lists as in the question.

``````list1, list2 = [list(tup) for tup in zip(*original)]
``````

Unpacks the two lists.

By : Noyer282

It's only another way to do it but it helped me a lot so I write it here:

Having this data structure:

``````X=[1,2,3,4]
Y=['a','b','c','d']
XY=zip(X,Y)
``````

Resulting in:

``````In: XY
Out: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
``````

The more pythonic way to unzip it and go back to the original is this one in my opinion:

``````x,y=zip(*XY)
``````

But this return a tuple so if you need an array you can use:

``````xy=(list(x),list(y))
``````
By : G M

I like to use `zip(*iterable)` (which is the piece of code you're looking for) in my programs as so:

``````def unzip(iterable):
return zip(*iterable)
``````

I find `unzip` more readable.

By : wassimans