# How To Use Reduce Function In Python

--

The aim of this pagešis to document the reduce() from the standard functools Python library. Reduce is a standard technique within functional programming - in other languages, it is known as fold or accumulate and typically combined with map and filter as brilliantly illustrated by prof. Abelson in the SICP Lecture on Streams.

## 1. DEFINE

• Repeatedly applies a function of two arguments to an interim accumulator value
• Each element of the series, in turn, updating (accumulating) the interim value with the result of the called function
• The initial value can be the first element in the input or an optional argument
• The final accumulated ā or reduced value is returned

## 2. EXAMPLE: SUMMATION OF A SEQUENCE

from functools import reduce
import operator

reduce(operator.add, [1, 2, 3, 4, 5])
numbers = [1, 2, 3, 4, 5]
for item in numbers[2:]:

print(accumulator)
>>> 15

## 3. PRINTING OUT REDUCTION

def mul(x, y):
print(f"mul {x} {y}")
return x * y

reduce(mul, range(1, 10))
"""
>>> reduce(mul, range(1, 10))
mul 1 2
mul 2 3
mul 6 4
mul 24 5
mul 120 6
mul 720 7
mul 5040 8
mul 40320 9
362880
"""

## 4. EMPTY SEQUENCE RAISES A TYPE ERROR

• I am using the mul function defined above
>>> reduce(mul, [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

## 5. SINGLE-ITEM ELEMENTS NEVER CALL REDUCE

>>> reduce(mul, [1])
1

## 6. OPTIONAL: INITIAL VALUE ARG

• this value is conceptually added to the beginning of the input sequence
• it, therefore, serves as the first accumulator value
• this means it is returned if the input sequence is empty
• useful if not sure that the input will have any values
>>> import operator
>>> values = [1,2,3]
6
• take care when selecting the initial value ā the correct value depends on the function you are applying
• i.e. do not take initial value 0 for multiplication :)
>>> values = [1,2,3]
>>> reduce(mul, values, 0)
mul 0 1
mul 0 2
mul 0 3
0
>>> reduce(mul, values, 1)
mul 1 1
mul 1 2
mul 2 3
6