Skip to content Skip to sidebar Skip to footer

How Do Keys Work In Min And Max?

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

Solution 1:

Explanation of the key argument

Key works like this:

a_list = ['apple', 'banana', 'canary', 'doll', 'elephant']

min(a_list, key=len)

returns 'doll', and

max(a_list, key=len)

returns '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:

>>>a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>importpprint>>>pprint.pprint(dict((i,i<5.3)foriina))
{0:True,
 1:True,
 2:True,
 3:True,
 4:True,
 5:True,
 6:False,
 7:False,
 8:False,
 9:False}

Why?

>>> min([True, False])
False>>> max([True, False])
True

Explanation

Why is True greater than False?

>>> True == 1True>>> False == 0True>>> issubclass(bool, int)
True

It turns out that True and False are very closely related to 1 and 0. They even evaluate the same respectively.

Solution 2:

because all values are either True or False. So the first one of each is chosen.

min([True, 1, False, 0])

will return False instead of 0 because both have the same value but False happens first

Your code uses a key function with only boolean values so, for min, the first False happens at the number 6. So it is the chosen one.

What you probably want to do is:

min(x for x inrange(10) if x < 5.3)

Post a Comment for "How Do Keys Work In Min And Max?"