6.7. Reduce

  • Reduce sequence using function

  • Built-in

>>> 1 + 2
3
>>> 1 + 2 + 3 + 4
10

6.7.1. Syntax

6.7.2. Problem

>>> def add(x, y):
...     return x + y
>>>
>>>
>>> DATA = [1, 2, 3, 4]
>>> result = 0
>>>
>>> for element in DATA:
...     result = add(result, element)
>>>
>>> print(result)
10

6.7.3. Solution

>>> from functools import reduce
>>>
>>>
>>> def add(x, y):
...     return x + y
>>>
>>>
>>> DATA = [1, 2, 3, 4]
>>>
>>> reduce(add, DATA)
10

6.7.4. Rationale

>>> from functools import reduce
>>> from operator import mul
>>>
>>>
>>> DATA = [1, 2, 3, 4]
>>>
>>> reduce(mul, DATA)
24
>>> from functools import reduce
>>>
>>>
>>> DATA = [1, 2, 3, 4]
>>>
>>> reduce(min, DATA)
1
>>> reduce(max, DATA)
4

6.7.5. Map Reduce

../../_images/idiom-reduce-mapreduce.gif

6.7.6. Assignments