I run through the following sequence of statements:
>>> a = range(10)
>>> min(a, key=lambda x: x < 5.3)
6
>>> max(a, key=lambda x: x < 5.3)
0
The min and max give the exact opposite of what I was expecting.
The python documentation on min and max is pretty sketchy.
Can anyone explain to me how the "key" works?
Explanation of the
key
argumentKey works like this:
returns
'doll'
, andreturns
'elephant'
You provide it with a function, and it uses the minimum or maximum of the results of the function applied to each item to determine which item to return in the result.
Application
If your function returns a boolean, like yours, for min it'll return the first of the minimum of True or False, (which is False) which would be 6 or the first of the max (True) which would be 0.
To see this:
Why?
Explanation
Why is
True
greater thanFalse
?It turns out that
True
andFalse
are very closely related to1
and0
. They even evaluate the same respectively.because all values are either
True
orFalse
. So the first one of each is chosen.will return
False
instead of0
because both have the same value butFalse
happens firstYour code uses a
key
function with only boolean values so, formin
, the firstFalse
happens at the number6
. So it is the chosen one.What you probably want to do is: