How To Use Reduce Function In Python

1. DEFINE

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]
accumulator = operator.add(numbers[0], numbers[1])
for item in numbers[2:]:
accumulator = operator.add(accumulator, item)

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

>>> 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

>>> import operator
>>> values = [1,2,3]
>>> reduce(operator.add, values, 0)
6
>>> 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

7. LINKS

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store