0 votes
1 view
in Python by (47.8k points)

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.

2 Answers

0 votes
by (107k points)

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
by (20.3k points)

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.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...