If I have, for example, a list of tuples such as
a = [(1,2)] * 4
how would I create a list of the first element of each tuple? That is,
There are several ways:
>>> a = [(1,2)] * 4
>>> # List comprehension
>>> [x for x, y in a]
[1, 1, 1, 1]
>>> # Map and lambda
>>> map(lambda t: t[0], a)
[1, 1, 1, 1]
>>> # Map and itemgetter
>>> import operator
>>> map(operator.itemgetter(0), a)
[1, 1, 1, 1]
The technique of using map fell out of favor when list comprehensions were introduced, but now it is making a comeback due to parallel map/reduce and multiprocessing techniques:
>>> # Multi-threading approach
>>> from multiprocessing.pool import ThreadPool as Pool
>>> Pool(2).map(operator.itemgetter(0), a)
[1, 1, 1, 1]
>>> # Multiple processes approach
>>> from multiprocessing import Pool
>>> def first(t):
return t[0]
>>> Pool(2).map(first, a)
[1, 1, 1, 1]