Python: Unzipping the zip

(Original post from 25. March 2012)

I just came across a great little feature of python that I thought I might want to share with my non-existent fan base (and with myself).

While writing on my eternal project of a good role-playing music player, I came across a situation where I had to handle lists of tuples with two values. Often times, I found myself need to pass a list of just one part of that tuple to a function or some such thing and I was hunting high and low for a way to do it until a thought struck me.

One way to make these lists in python is to “zip” two lists together. Is there a way to “unzip”, i.e. the reverse of zip, such a list? turns out there is, but to me it is a bit a weird.

Here is an example:

>>> li = [(1, "one"), (2, "two"), (3, "three"), (4, "four")]
>>> zip(*li)
[(1, 2, 3, 4), ('one', 'two', 'three', 'four')]

As you can see, the two original lists are re-established. As long as the tuples have the same length, you can do this with as many items in a tuple as you want. I found this very useful and I found myself over using it a little bit.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s