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?
You’ve stumbled on to a difference in the implementation of
.sortandmaxmore 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 akey=Noneargument or it just taking on the default value. In either case, it behaves as if no key function has been provided.maxon 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: