Fast argmax in Python

In my post Computing argmax fast in Python, I reported that Python has no builtin function to compute argmax, the position of a maximal value. I provided one such function and asked people to improve my solution. Here are the results:

argmax function running time
array.index(max(array)) 0.1 s
max(izip(array, xrange(len(array))))[1] 0.2 s

Conclusion: array.index(max(array)) is simpler and faster.

Update: Please see The language interpreters are the new machines.

Daniel Lemire, "Fast argmax in Python," in Daniel Lemire's blog, December 17, 2008, https://lemire.me/blog/2008/12/17/fast-argmax-in-python/.
[BibTeX]

Published by

Daniel Lemire

A computer science professor at the University of Quebec (TELUQ).

7 thoughts on “Fast argmax in Python”

  1. Complexity of these operations with regard to array length would be more interesting. I think that your conclusion is a bit too wide.

  2. def argmax(a_list,key=lambda x:x):
    index = 0
    maxval = key(a_list[0])
    for i,e in enumerate(a_list[1:],1):
    v = key(e)
    if v > maxval:
    index = i
    maxval = v
    return index

    def argmax2(a_list,key=lambda x:x):
    index, value = max(enumerate(a_list), key=lambda y:key(y[1]))
    return index

  3. I’m sorry that the previous comment was malformatted.

    def argmax(a_list,key=lambda x:x):
    index = 0
    maxval = key(a_list[0])
    for i,e in enumerate(a_list[1:],1):
    v = key(e)
    if v > maxval:
    index = i
    maxval = v
    return index

    def argmax2(a_list,key=lambda x:x):
    index, value = max(enumerate(a_list), key=lambda y:key(y[1]))
    return index

Leave a Reply

Your email address will not be published.

You can also subscribe by email to this blog (non-commercial, no ads, weekly email).

How to post code (C, C++, Java, Python, etc.):

Wrap your code in backticks, like this:

`int main() {
    return 0;
}`