Sylvester V Lowell
Sylvester V Lowell

Reputation: 1323

Python min and max functions, but with indices

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

Upvotes: 3

Views: 449

Answers (4)

Maxim Razin
Maxim Razin

Reputation: 9466

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

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

Upvotes: 0

kenm
kenm

Reputation: 23975

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

Upvotes: 2

Blender
Blender

Reputation: 298512

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.

Upvotes: 5

Russell Dias
Russell Dias

Reputation: 73382

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

Upvotes: 6

Related Questions