Is there a simple way to find the list index to the max value?

A

Arnaud Delobelle

See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2.

The most obvious would be a.index(max(a)). Is that what you wanted ?

The disadvantage of that is that it's O(2N) instead of O(N).

:)

Joke aside, even though you traverse the list twice, it may still be
quicker than other solutions because both max and list.index are C
functions and no intermediate object is constructed.
 
T

TomF

See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2.

The most obvious would be a.index(max(a)). Is that what you wanted ?

The disadvantage of that is that it's O(2N) instead of O(N).

I don't think you understand order notation. There's no such thing as O(2N).

To answer the original question, how about:
max(enumerate(l), key=lambda x: x[1])[0]
As to whether this is faster than index(max()), you'd have to time it.

-Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top