Tweaking the Standard Behavior of min() and max()
The goal is to modify the comparison criteria to use in finding the minimum or maximum value. As an example of how this feature can be useful, let’s say you have a list of numbers as strings and want to find the smallest and largest numbers. If you process the list directly with
max(), then you get the results seen on-screen.
00:55 Now, these may not be the results you need or expect. You are getting the smallest and largest strings based on Python’s string comparison rules rather than based on the actual numeric value of each string.
Now, the result of
max() depends on the numeric values of the underlying strings. Note that you don’t need to call
int(). You just pass
int without the pair of parentheses because
key expects a function object or, more accurately, a callable object. Callable objects in Python include functions, methods, classes, and instances of any class that provides a
.__call__() special method.
Remember that this argument is only available when you call the function with a single iterable as an argument. The job of
default is to provide a suitable default value as the return value of
max() when it’s called with an empty iterable.
Become a Member to join the conversation.