Python: inverse of zip

So you have a list of tuples, created with the zip built-in function in Python. Like this:

z = [(1, 'a'), (2, 'b'), (3, 'c')]

And you want to reverse zip, to get these two lists:

x = [1, 2, 3]
y = ['a', 'b', 'c']

You could invoke map in a wierd way:

x = []
y = []
map(lambda (a,b): x.append(a) or y.append(b), z)
# Returns [None, None, None]
# x: [1, 2, 3]
# y: ['a', 'b', 'c']

It feels like there should be a solution in itertools. Just haven't found it yet...

2 thoughts on “Python: inverse of zip”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.