I was once working with some data in Python that would generate a list of tuples, for example:

myList = [('ab',1), ('cd', 2), ('ef', 3)]

I wanted to obtain two lists from this: the first list containing the first element of each tuple and the second list containing the second element of each tuple. The zip function goes part of the way there:

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

Effectively, zip would produce two tuples. Individually converting these to a list (e.g. list(a) and list(b)) would work, but would not be feasible if the tuples had many more entries. This is where the map function comes in:

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

At this point, I also found out that Python’s syntax also supports pointers directly to list, such that:

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

works! I forget that Python syntax can differ from C!

Next Post Previous Post