Newbie: finding the key/index of the min/max element

Alex Martelli aleax at aleax.it
Tue Apr 30 17:23:05 EDT 2002


Benjamin Han wrote:

> In my quest of becoming a "Pythonistas" (where does this word come from

I think it's plural, and the singular "Pythonista".

> BTW?), here comes my 2nd trivial question: how do you find the key/index
> of the max/min element in a sequence/map? I know you can call max(l) but
> this only gives you the element itself, not the key. I also know it's not
> that hard to code it up the hard way (for k in d.keys(): ... # do
> comparison), but is there a more elegant way of doing this?

For a list, you _might_ do L.index(max(L)) -- that's conceptually two
passes on the list, but performance should still be OK.

This doesn't work for a mapping, though.  However, for a mapping (assuming
Python 2.2, else you need to iterate on D.keys() rather than on D):

        max([ (D[key], key) for key in D ])[1]

works (a variation of the DSU pattern -- we could call it DEU, for 
Decorate, Extremal, Undecorate:-).

As to whether this is "more elegant" than a loop -- I'll pass.


Alex




More information about the Python-list mailing list