Reverse zip() ?

John Machin sjmachin at lexicon.net
Tue Dec 2 19:14:46 EST 2008


On Dec 3, 7:12 am, Stefan Behnel <stefan... at behnel.de> wrote:
> Andreas Waldenburger wrote:
> > we all know about the zip builtin that combines several iterables into
> > a list of tuples.
>
> > I often find myself doing the reverse, splitting a list of tuples into
> > several lists, each corresponding to a certain element of each tuple
> > (e.g. matplotlib/pyplot needs those, rather than lists of points).
>
> > This is of course trivial to do via iteration or listcomps, BUT, I was
> > wondering if there is a function I don't know about that does this
> > nicely?
>
> I think you're asking about zip():
>
>         >>> l=[1,2,3]
>         >>> zip(l,l)
>         [(1, 1), (2, 2), (3, 3)]
>         >>> zip(*zip(l,l))
>         [(1, 2, 3), (1, 2, 3)]
>

Here's a version that makes it slightly easier to comprehend:

Q: I know how to zip sequences together:
| >>> a = (1, 2, 3)
| >>> b = (4, 5, 6)
| >>> z = zip(a, b)
| >>> z
| [(1, 4), (2, 5), (3, 6)]
but how do I reverse the process?

A: Use zip()!
| >>> a2, b2 = zip(*z)
| >>> a2
| (1, 2, 3)
| >>> b2
| (4, 5, 6)

Cheers,
John



More information about the Python-list mailing list