reduce()
Another common higher order function in functional programming is reduce
.
This can be found in the functools
module
We won’t spend too long on this, because there are better and easier ways to achieve what reduce
can do in Python. There is a reason why reduce
is not a built-in function in Python 3! I’ve included it here purely for educational purposes!
functools.reduce(func, iterable)
applies func
cumulatively to pairs of items in iterable
(from left to right), and reduces them to a single value.
This is probably easier to explain with an example. The code below computes (((1+2)+3)+4)+5)
from functools import reduce
numbers = [1, 2, 3, 4, 5]
cumulative_sum = reduce(lambda x, y: x+y, numbers)
print(cumulative_sum) # 15
You can also provide the initializer
argument to reduce()
, which will be placed before the iterable
in the calculation.
print(reduce(lambda x, y: x+y, numbers, 10)) # 25
print(reduce(lambda x, y: x+y, [], 10)) # 10
The list comprehension version is actually more Pythonic (and more readable, and thus recommended).
cumulative_sum = sum([number for number in numbers])
If you want more examples of reduce
(and better ways to achieve this in Python), see this article.