The documentation for the built-in functions max
and min
in Python indicate that the key
parameter should operate like it does in the sort
function. In other words, I should be able to do this:
a = [1, 2, 3, 4]
max(a, key=None)
However, this raises an error:
TypeError: 'NoneType' object is not callable
But, if I do something similar with the sort
function, I get the expected results:
a = [1, 2, 3, 4]
a.sort(key=None)
No error is generated and the default sort is used. Several books also imply that I should be able to get away with the same behavior in the max
and min
functions. See this excerpt from Python in a Nutshell.
Is this really the default behavior of the max
and min
functions? Should it be? Shouldn't they match the sort function?
key (optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable. If max() is called with an iterable, it returns the largest item in it. If the iterable is empty then the default value is returned, otherwise, a ValueError exception is raised.
Python max() Function The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.
Output The smallest key: -2 The key with the smallest value: -1 The smallest value: 1. In the second min() function, we have passed a lambda function to the key parameter. key = lambda k: square[k] The function returns the values of dictionaries.
Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.
You've stumbled on to a difference in the implementation of .sort
and max
more than a problem with the language.
list.sort()
takes a keyword argument "key" which happens to default to None. This means that the sort method can't tell the difference between you supplying a key=None
argument or it just taking on the default value. In either case, it behaves as if no key function has been provided.
max
on the other hand is checking for the presence of a keyword argument "key". It does not have a default value and it's value is used as the key function if present at all.
Either way, key should never be supplied as None. It is supposed to be a function which is used to extract a "key" value from the items in the list/iterable. For instance:
a = [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
a.sort(key=lambda item:item[1])
@David's answer is perfect. Just adding, in case you're wondering, the default key
value (both in sort
and in max
/min
functions) is something like:
lambda x: x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With