Using the built-in reductions – max, min, and reduce
We have two other built-in higher-order functions that can accept functions as arguments. These can be characterized as reductions: they reduce a collection of values to a single value. There's a third built-in reduction, sum, but it's not a proper higher-order function: we can't tailor its operation by plugging in a function.
The max()
and min()
reductions follow the design pattern for the sorted()
function: they accept an iterable object first, and they can be customized with an optional key function. We'll show the default behavior first, then we'll show how to customize this with the key function:
>>> data = ["21", "3", "35", "4"] >>> min(data) '21' >>> min(data, key=int) '3'
In the first example, the string objects were compared using string comparison. This leads to the anomaly of seeing "21"
appear to be less than "3"
. In fact, a string beginning with "2"
is sorted before a string beginning with "3"
, but...