Getting Started With min() and max()
Getting Started With Python’s
max() Functions. Python includes several built-in functions that make your life more pleasant and productive. They mean you don’t need to reinvent the wheel.
Two such functions are
max(). They mostly apply to iterables, but you can use them with multiple regular arguments as well. As their names suggest, they take care of finding the smallest and largest values in input data.
Whether you’re using Python’s
max(), you can use the function to achieve two slightly different behaviors. The standard behavior for each is to return the minimum or maximum value through straightforward comparison of the input data as it stands.
The alternative behavior is to use a single-argument function to modify the comparison criteria before finding the smallest and largest values. To explore the standard behavior of
max(), you can start by calling each function with either a single iterable as an argument or with two or more regular arguments, and that’s what you’ll do straight away.
They also take two optional keyword-only arguments:
key. On-screen is a summary of what the arguments to
max() do. In these signatures, the asterisk (
*) means that the following arguments are keyword-only arguments, while the square brackets denote that the enclosed content is optional.
Later in this course, you’ll learn more about the optional
key arguments. For now, just focus on the
iterable argument, which is a required argument that leverages the standard behavior of
max() in Python.
The first call to
min() returns the smallest number in the input list—in this case,
-5. If you pass an empty iterator to
max(), then you get a
ValueError because there’s nothing to do on an empty iterable.
You can’t call
max() with an iterable of noncomparable types as an argument. In this example, a function tries to compare a number to a string, which is like comparing apples and ladders.
default value isn’t required because you’ll always have at least two values to compare in order to find the minimum or maximum. You can see this alternative signature in use on-screen. You
Become a Member to join the conversation.