Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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.6k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...