Today we’ll be talking about the reduce function, which, unlike the map and filter functions discussed in the previous articles, is not a built-in function. We have to import it from the functools module like so:
from functools import reduce
By the way, if you want to learn more about the other two functions used in functional programming, feel free to read my articles on the map and filter functions.
Here’s the video version of the article:
And now back to the reduce function. The function applies a function to pairs of elements of an iterable object cumulatively, working from left to right. The output is not an iterable, it’s a simple object, like a number or string.
Make sure to read my article about iterables and iterators if you want to learn more about what they are.
reduce Function with Strings Example
Here’s an example with a lambda function that concatenates the strings in the iterable (the syllables list):
from functools import reduce
syllables = ["un", "be", "lie", "va", "ble"]
word = reduce(lambda x, y: x + y, syllables)
print(word)
Here’s the output:
unbelievable
An Example with Numbers
Now an example with numbers and with a regular function. This time we get the product of all the numbers in the list:
from functools import reduce
def multiplier(x, y):
return x * y
numbers = [3, -1, 2, 5, 7]
product = reduce(multiplier, numbers)
print(product)
And the output is:
-210
Let’s take the last example to explain how the reduce function actually works. Here are the steps:
1. The multiplier function is applied to the first two elements: multiplier(3, -1), which returns the product: -3.
2. The multiplier function is applied to the product and the third element: multiplier(-3, 2), which returns the product: -6.
3. The multiplier function is applied to the product and the fourth element: multiplier(-6, 5), which returns the product: -30.
4. The multiplier function is applied to the product and the fifth element: multiplier(-30, 7), which returns the product: -210. There are no more elements in the list, so this is the final result returned by the reduce function.
Schematically, the reduce function in our example works like so:
multiplier(multiplier(multiplier(multiplier(3, -1), 2), 5), 7)
or in a more visual way: