How to split a list of 2-tuples into two lists?

a,b = zip(*y)

is all you need ...

or if you need them as lists and not tuples

a,b = map(list,zip(*y))

Use zip and a list comprehension:

>>> y = [('ab', 1), ('cd', 2), ('ef', 3)]
>>> a,b = [list(c) for c in zip(*y)]
>>> a
['ab', 'cd', 'ef']
>>> b
[1, 2, 3]
>>>

zip with * argument unpacking will give you tuples:

>>> a, b = zip(*y)
>>> a
('ab', 'cd', 'ef')
>>> b
(1, 2, 3)

If you need lists, you can use map on that:

>>> a, b = map(list, zip(*y))
>>> a
['ab', 'cd', 'ef']
>>> b
[1, 2, 3]

Tags:

Python

List