Index of maximum element in list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Jan 26 10:51:51 CET 2008


> Henry Baxter wrote:
> > def maxi(l):
> >     m = max(l)
> >     for i, v in enumerate(l):
> >         if m == v:
> >             return i
>
> What's about l.index(max(l)) ?

The version I use:

def posmax(seq, key=None):
    """Return the position of the first maximum item of a sequence.
    It accepts the usual key parameter too."""
    if key:
        return max(enumerate(seq), key=lambda k: key(k[1]))[0]
    else:
        return max(enumerate(seq), key=itemgetter(1))[0]

Bye,
bearophile



More information about the Python-list mailing list