How is max supposed to work, especially key.

Chris Angelico rosuav at gmail.com
Thu Dec 4 05:18:46 EST 2014


On Thu, Dec 4, 2014 at 9:09 PM, Albert van der Horst
<albert at spenarnc.xs4all.nl> wrote:
>>If there is more than one item with the maximum calculated the first is
>>given, so for your attempt
>>
>>max(xrange(100,200), key=lambda i: i%17==0 )
>
>>
>>the values False, False, True, False, ... are calculated and because
>>
>>>>> True > False
>>True
>>
>>the first one with a True result is returned.
>>
>
> So in that case max doesn't return the maximum (True), but instead
> something else.
>
> Useful as that function may be, it shouldn't have been called max.
>
> I don't blame myself for being misled.

If lots of them are equally the largest, by whatever definition of
largest you have, it has to do one of three things:

1) Raise an exception
2) Return multiple items (either as a tuple, or a generator, or something)
3) Pick one of them and return it.

Python's max() does the third, and for the picking part, uses the
first one it comes across - a decent way to do it.

If there's no clear maximum, it can't do any better than that. It's
still returning something for which there is no greater.

ChrisA



More information about the Python-list mailing list