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, ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.