Index of maximum element in list

Paul Rubin http
Sun Jan 27 06:42:33 EST 2008


Arnaud Delobelle <arnodel at googlemail.com> writes:

> def simple_posmax(l, key=None):
>     if key:
>         return l.index(max(l, key=key))
>     else:
>         return l.index(max(l))

def simple_posmax(l, **kw):
   return l.index(max(l, **kw))

> simple_posmax is more than 3x faster on my machine.  It's not
> surprising as even though the list is walked twice, it is all done in
> C and no new objects have to be created. Then only non-C bit is when
> the result of max(l) is fed to l.index().

It does expose a slight danger in that the list might somehow
self-mutate during the first traversal.



More information about the Python-list mailing list