How is max supposed to work, especially key.

Jussi Piitulainen jpiitula at ling.helsinki.fi
Thu Dec 4 07:58:00 EST 2014


Steven D'Aprano writes:
> Jussi Piitulainen wrote:
> 
> > Would you also want sorted called something else when used with a
> > key?  Because it doesn't produce a sorted list of the keys either:
> > 
> >   >>> data = ("short", "long", "average")
> >   >>> sorted(data, key=len)
> >   ['long', 'short', 'average']
> >   >>> max(data, key=len)
> >   'average'
> 
> I agree with the point you are making, but I disagree with the
> wording you use. The result of calling sort() with key=len *is*
> sorted. It is sorted by length of the word.

It's sorted but it's not a list of the keys. That seemed to be a point
of contention about naming max-with-key max: it doesn't return a key.

> Same for calling max() with a key. The result is still the maximum
> value.  The difference is how you decide which of two elements is
> greater:
> 
> max(list_of_foods, key=calories)
> max(list_of_foods, key=weight)
> max(list_of_foods, key=cost)
> 
> That is three different ways to decide which is the maximal food in
> the list: by number of calories, by weight, or by cost.

Yes. I don't see any disagreement between us.



More information about the Python-list mailing list