Does Python have a built-in function like min() and max() except that it returns the index rather than the item?
4 Answers
There's no builtin, but min and max take a key argument, which lets you do something like this:
from operator import itemgetter
index, elem = min(enumerate(iterable), key=itemgetter(1))
This works for any iterable, not just lists.
2 Comments
martineau
Nice answer, but the
index() method in the currently accepted one handles any sequence type (str, unicode, list, tuple, bytearray, buffer, xrange in Python 2.x), which is likely generic enough for most purposes, I suspect.Ben Hoyt
I really like this, and I thought it would be faster, as it only has to iterate the list once, whereas
lst.index(min(lst)) has to iterate twice. But even on large (10,000 element) lists, timeit tells me index+min is about twice as fast. :-)