Higher Order Functions in Python — map(), filter(), and reduce()

Original article was published on Artificial Intelligence on Medium

Reduce Elements

The third function that we’re going to discuss is the reduce() function. Unlike the map() and filter() functions which are built-in functions, the reduce() function is available in the functools module. The reduce() function takes a function and an iterable. The reduce() function will apply the function to the elements of the iterable using the rolling result cumulatively before it arrives at a final output value.

For example, if the iterable is [a, b, c, d], we’ll get the result of a certain operation between a and b, say the result is X, and the next step will be to get the result for X and c to produce Y, and Y and d will produce the final output value. Let’s see how reduce() works with the following example.

There are a few things to note.

  • We use a lambda function that adds two numbers. Importantly, the function that can be passed to the reduce() function needs to take exactly two elements.
  • The last argument in the reduce() function call is termed initial, which sets the initial value for the cumulative operation. In the example below, the sum(primes) is 41. With the initials of 1 and 5, the final results are 42 and 46, respectively.
>>> # Import the needed module
>>> from functools import reduce
>>>
>>> # Create a list for reducing
>>> primes = [2, 3, 5, 7, 11, 13]
>>>
>>> # Reduce the list
>>> total0 = reduce(lambda x, y: x + y, primes, 1)
>>> total0
42
>>> total1 = reduce(lambda x, y: x + y, primes, 5)
>>> total1
46

The above code is a very trivial example on reduce(), because as indicated above, we can simply use the sum() function to calculate the total. So the question is that what the reduce() function can be used in a more realistic scenario. Consider the following example that uses the reduce() function to calculate factorials (e.g., 3! = 6, 4! = 10). Pretty cool, right?

>>> # Define a function that uses the reduce() function
>>> def factorial(n):
... return 1 if n < 2 else reduce(lambda x, y: x*y, range(1, n+1))
...
>>> # Create a list consisting of factorials
>>> factorials = [factorial(x) for x in range(10)]
>>> factorials
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

As a side note, the two lambda functions are basic operations that are actually available in the operator module. See the pertinent examples below.

>>> # Import the operator functions
>>> from operator import add, mul
>>>
>>> # Comparisons
>>> reduce(lambda x, y: x+y, [2, 3, 4])
9
>>> reduce(add, [2, 3, 4])
9
>>> reduce(lambda x, y: x*y, [1, 2, 3])
6
>>> reduce(mul, [1, 2, 3])
6