Creating the min_max() Function
Here you start to define
min_max(). The function’s first portion standardizes the input data for further processing. Because the user will be able to call
min_max() with either a single iterable or with several regular arguments, you need to check the length of
To do this, you use the built-in
len() function. If
args holds only one value, then you need to check that the argument is an iterable object. You use
list(), which implicitly does the check and also turns the input iterable into a list.
Note that you use the
from None syntax to hide away the traceback of the original
else branch runs when
args holds more than one value, which handles the cases where the user calls the function with several regular arguments instead of with a single iterable of values.
If this conditional doesn’t ultimately raise a
values will hold a list of values that may be empty. Even if the resulting list is empty, it’s now clean and ready for continuing the process of finding its minimum or maximum value.
default is returned. This behavior emulates the standard behavior of
max() when you call them with empty iterables. Next, you need to process the
key argument and prepare the data for finding the smallest and largest values according to the provided
key. First, you check if the user hasn’t provided a
On the other hand, if the user has provided a
key argument, then you need to make sure that the argument is actually a function or callable object. To do this, you use the built-in
callable() function, which returns
True if the argument is callable and
Once you’re sure that
key is callable, then you build a list of comparison keys by applying
key to each value in the input data. Finally, if
key isn’t a callable object, then the
else clause runs, raising a
TypeError, just as
Every loop operation compares the current key to the tentative minimum or maximum and updates the values of
extreme_value. Accordingly, at the end of the loop, these variables will hold the minimum or maximum key and its corresponding value. Finally, you just need to return the value in
Become a Member to join the conversation.