[Python-Dev] adding key argument to min and max

Raymond Hettinger python at rcn.com
Thu Dec 2 00:23:29 CET 2004


[Steven Bethard]
> For Python 2.5, I'd like to add a keyword argument 'key' to min and
> max like we have now for list.sort and sorted. 
 . . .
> This means that a 'key'
> argument can *only* be specified as a keyword parameter, thus giving
> us the asymmetry we see in these examples.

FWIW, in Py2.5 I plan on adding a key= argument to heapq.nsmallest() and
heapq.nlargest().  There is no "assymmetry" issue with those functions,
so it can be implemented cleanly.  And, since min/max are essentially
the same nsmallest/nlargest with n==1, your use case is covered and
there is no need to mess with the min/max builtins.



> I've needed this a couple of times now, specifically when 
> I have something like a dict of word counts, and I want the most
frequent word

For Py2.4, you can cover your use cases readily adding the recipe for
mostcommon() to a module of favorite utilities:

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347615

Alternatively, the recipe for a bag class is a more flexible and still
reasonably efficient:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259174



Raymond Hettinger



More information about the Python-Dev mailing list