Python function that returns value at index 0?

Does the Python standard library have a function that returns a value at index 0? In other words:

zeroth = lambda x: x[0] 

I need to use this in a higher order function like map() . I ask because I believe it is clearer to use the reusable function rather than defining a custom one, for example:

 pairs = [(0,1), (5,3), ...] xcoords = map(funclib.zeroth, pairs) # Reusable vs. xcoords = map(lambda p: p[0], pairs) # Custom xcoords = [0, 5, ...] # (or iterable) 

I also ask because Haskell has a Data.List.head function that is useful as an argument to higher order functions:

 head :: [a] -> a head (x:xs) = x head xs = xs !! 0 xcoords = (map head) pairs 
+7
python dictionary list lambda
source share
3 answers

You need to use operator.itemgetter

 >>> import operator >>> pairs = [(0,1), (5,3)] >>> xcoords = map(operator.itemgetter(0), pairs) >>> xcoords [0, 5] 

In Python3, map returns a map object, so you need a list call.

 >>> list(map(operator.itemgetter(0), pairs)) [0, 5] 
+6
source share

The most Python approach would probably use operator.itemgetter(0) . It returns just such a function.

Another approach would be to call obj.__getitem__ . This is smaller than Pythonic because it explicitly invokes special method names, and does not allow Python to infer what to call internally.

+3
source share

With the concept of:

 >>> pairs = [(0,1), (5,3)] >>> xcoords = [ t[0] for t in pairs ] >>> xcoords 
0
source share

All Articles