Reducing with operator module functions

We'll look at one more way that we can use the operator definitions. We can use them with the built-in functools.reduce() function. The sum() function, for example, can be defined as follows:

sum = functools.partial(functools.reduce, operator.add)

This creates a partially evaluated version of the reduce() function with the first argument supplied. In this case, it's the + operator, implemented via the operator.add() function.

If we have a requirement for a similar function that computes a product, we can define it like this:

prod = functools.partial(functools.reduce, operator.mul)

This follows the pattern shown in the preceding example. We have a partially evaluated reduce() function with the first ...

Get Functional Python Programming - Second Edition 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.