Index of maximum element in list

Arnaud Delobelle arnodel at googlemail.com
Sun Jan 27 07:03:08 EST 2008


On Jan 27, 11:42 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Arnaud Delobelle <arno... 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))

Yes.  I wanted to make simple_posmax and clever_posmax as identical as
possible to make the comparison fair.

>
> > 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.

I suppose.  Although you'd have to be mad to have comparisons mutate
stuff...
Also, it only works with sequences.
--
Arnaud




More information about the Python-list mailing list