Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function that returns the value at index 0?

Does the Python standard library have a function that returns the 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's clearer to use a reusable function rather than define 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 does have such a function Data.List.head, which is useful as an argument to higher-order functions:

head :: [a] -> a
head (x:xs) = x
head xs = xs !! 0

xcoords = (map head) pairs
like image 753
Nayuki Avatar asked Dec 19 '15 18:12

Nayuki


2 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, hence you need a list call over it.

>>> list(map(operator.itemgetter(0), pairs))
[0, 5]
like image 58
Bhargav Rao Avatar answered Oct 23 '22 10:10

Bhargav Rao


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

Another approach would be to call obj.__getitem__ directly. It's less Pythonic because it explicitly calls special method names, instead of allowing Python to infer what to call internally.

like image 24
kojiro Avatar answered Oct 23 '22 09:10

kojiro