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

James J. Besemer jb at cascade-sys.com
Tue Apr 30 17:36:58 EDT 2002


Benjamin Han wrote:

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

The term derrives from the Sandinistas in Nicaragua, the Communist rebels who
fought against the US-installed conservative Somoza dictatorship (and others).
The suffix is sometimes used to refere to any contrarian group, and in cases
simply any group.

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

I have trouble thinking of a clearer or more efficient way than simply iterating
on the list.

There's a lot of other ways to do it if you goal is to get rid of the for loop,
but I think they're all less efficient and I'm not sure you could say any are more
elegant.

E.g., you could say

    x = min( list )
    minkey = list.index( x )

and do it in "two steps".  But this actually requires on average 1.5 comparisons
on the list, one to find the min and however many checks it takes to find that
value again.

Then too, for small lists performance need not be a consideration.  However, I
personally would avoid obfuscating the matter with auxilliary lists or data
structures, even though it's insanely easy to do.

Sometimes a cigar is simply a cigar.

Regards

--jb

--
James J. Besemer  503-280-0838 voice
http://cascade-sys.com  503-280-0375 fax
mailto:jb at cascade-sys.com







More information about the Python-list mailing list