3

Does Python have a built-in function like min() and max() except that it returns the index rather than the item?

4 Answers 4

6

There is no inbuilt function for that. You can just do your_list.index(min(your_list)).

Sign up to request clarification or add additional context in comments.

Comments

5

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

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.
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. :-)
2

If you have NumPy, it has argmax and argmin functions you can use.

Comments

0

min has a key= argument, you can try something like

min(range(len(mylist)), key=mylist.__getitem__)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.