This is what operator.itemgetter
is for.
>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b
[1, 2]
The itemgetter
statement returns a function that returns the index of the element you specify. It's exactly the same as writing
>>> b = map(lambda x: x[0], a)
But I find that itemgetter
is a clearer and more explicit.
This is handy for making compact sort statements. For example,
>>> c = sorted(a, key=operator.itemgetter(0), reverse=True)
>>> c
[(2, u'def'), (1, u'abc')]