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.

Login

0 votes

There is no need for any built-in function for transposing Zip because Zip is its own inverse. There is a special * operator which does all the tasks:-

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])

[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

It works by calling zip with the arguments:

zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))

0 votes

If you have lists that are not of the same length, then you may not want to use zip as per Patrick's answer.

This will work:

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])

[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

But with different length lists, zip truncates each item to the length of the shortest list:

>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])

[('a', 'b', 'c', 'd', 'e')]

You can also use map with no function to fill empty results with None:

>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])

[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]

zip() is marginally faster though.