Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Tweaking the Standard Behavior of min() and max()

00:00 Tweaking the Standard Behavior of min() and max() With key and default. Up to this point, you’ve learned how min() and max() work in their standard form.

00:10 In this section of the course, you’ll learn how to tweak the standard behavior of both functions by using the key and default keyword-only arguments.

00:18 The key argument to min() or max() allows you to provide a single-argument function that will be applied to every value in the input data.

00:26 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 min() and 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.

01:07 In this case, the solution is to pass the built-in int() function as the key argument to min() and max(), as seen on-screen.

01:25 Now, the result of min() and 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.

01:53 The second keyword-only argument that allows you to customize the standard behavior of min() or max() is default.

01:59 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 min() or max() when it’s called with an empty iterable.

02:23 Here, the empty iterable is an empty list. The standard behavior for min() or max() is to raise a ValueError complaining about the empty sequence argument.

02:32 But because you supplied a value to default, both functions now return this value instead of raising an exception and breaking your code.

02:42 In the next section of the course, you’ll take a look at using min() and max() with comprehensions and generator expressions.

Become a Member to join the conversation.