key argument for max?

Raymond Hettinger python at rcn.com
Mon Oct 25 02:33:08 EDT 2004


[Steven Bethard]
> I was wondering if there's any plans to add a "key" argument to max
> (and min) like was done for sort(ed)?  

Someday maybe.  In the meantime, here's a recipe:


from itertools import imap, izip, tee

def newmax(*args, **kwds):
    """Works just like max() but allows an optional key= argument.

    If several keys are equal and maximum, may return any one of them.
    """
    if 'key' not in kwds:
        return max(*args)
    func = kwds['key']

    if len(args) == 1:
        v = args[0]
    else:
        v = args
    v1, v2 = tee(v)
    return max(izip(imap(func, v1), v2))[-1]



> If this seems like a good idea, maybe someone could point me in the
> right direction and I could try to make a patch?  I've never looked at
> the Python sources before, and it's been a long time since I've
> written any C, but if it's not too hard...

See dist/src/Python/bltinmodule.c
Add the keyword argument.
If it exists apply the function on each iteration before the
comparision step.

The only part that requires extra care is realizing that the key
function and the comparison step may call arbitrary Python code, so
don't assume that any mutable objects are still in the same state
before and after those calls.



Raymond Hettinger



More information about the Python-list mailing list