5.8. Reduce

5.8.1. Rationale

  • Reduce sequence using function

  • Built-in

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

5.8.2. Syntax

5.8.3. Problem

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

5.8.4. Solution

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

5.8.5. Use Cases

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

5.8.6. Map Reduce

../../_images/designpatterns-idioms-mapreduce.gif

5.8.7. Assignments