Unpacking a list / tuple of pairs into two lists / tuples
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Question
00:40 Accepted answer (Score 493)
01:14 Answer 2 (Score 36)
01:24 Thank you
--
Full question
https://stackoverflow.com/questions/7558...
Question links:
[A Transpose/Unzip Function in Python]: https://stackoverflow.com/questions/1933...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #tuples
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Question
00:40 Accepted answer (Score 493)
01:14 Answer 2 (Score 36)
01:24 Thank you
--
Full question
https://stackoverflow.com/questions/7558...
Question links:
[A Transpose/Unzip Function in Python]: https://stackoverflow.com/questions/1933...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #tuples
#avk47
ACCEPTED ANSWER
Score 552
>>> source_list = [('1','a'),('2','b'),('3','c'),('4','d')]
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable) is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
ANSWER 2
Score 41
list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)