Default key for Python built-in functions max / min

The documentation for the built-in max and min functions in Python indicates that the key parameter should work just like in the sort function. In other words, I have to do this:

 a = [1, 2, 3, 4] max(a, key=None) 

However, this causes an error: TypeError: 'NoneType' object is not callable

But, if I come down with the sort function, I get the expected results:

 a = [1, 2, 3, 4] a.sort(key=None) 

No error is generated and default sorting is used. Several books also imply that I have to get away with the same behavior in the max and min functions. See this excerpt from Python in a nutshell .

Is this the default behavior of the max and min functions? Should it be? Shouldn't they match the sort function?

+8
python
source share
2 answers

You stumbled upon the difference in the implementation of .sort and max more than the problem with the language.

list.sort() takes a key argument of "key", which defaults to "None". This means that the sorting method cannot determine the difference between the delivery of the key=None argument or just the default value. In any case, it behaves as if no key function was provided.

max , on the other hand, checks for the presence of the keyword "key". It does not have a default value, and its value is used as a key function, if present at all.

In any case, the key should never be delivered as None. This is supposed to be a function that is used to extract the "key" value from the items in the / iterable list. For example:

 a = [("one", 1), ("two", 2), ("three", 3), ("four", 4)] a.sort(key=lambda item:item[1]) 
+23
source share

@ David answers perfectly. Just adding, if you're interested, the default key value (in both sort and max / min functions) looks something like this:

 lambda x: x 
+7
source share

All Articles