key argument for max?

Alex Martelli aleaxit at yahoo.com
Fri Oct 22 07:33:09 EDT 2004


Steven Bethard <steven.bethard at gmail.com> wrote:

> I was wondering if there's any plans to add a "key" argument to max
> (and min) like was done for sort(ed)?  I fairly often run into a

Unfortunately, no.  I think that the excellent key= optional argument to
sort should be extended to every order-related Python tidbit; min and
max are examples, but so should the heapq module's functions.
Unfortunately, this idea wasn't liked by the python-dev consensus back
in 2.4's formative stages, and it's now too late for any functional
changes to 2.4.  So, we can take it up again for 2.5 at some time.

> situation where I have something like:
> 
> counts = {}
> for item in iterable:
>     counts[item] = counts.get(item, 0) + 1
> _, max_item = max((count, item) for item, count in counts.items())
> 
> It would be nice to be able to write that last like like:
> 
> max(counts, key=counts.__getitem__)

One crucial aspect that any key= should maintain is never to compare
items that happen to have equal keys.  So, I think the semantics of that
line should rather be those of:

    max((counts[item], i, item) for i, item in enumerate(counts))[-1]

i.e. inserting an index (arbitrary in this case, as counts is a
dictionary) that will never be equal so no two items are compared.

If you _want_ to compare items, when they have the same count, you
should say that explicitly -- the default should be that key= means no
item comparison, for uniformity.  Unfortunately being explicit _and_
compact at the same time generally requires a lambda, such as:

    max(counts, key=lambda item: counts[item], item)


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

It's not too hard, but such a patch would not be accepted for Python
2.4, and it's a bit early to start making patches for 2.5, sigh.


Alex



More information about the Python-list mailing list