4.6. Reduce

4.6.1. Rationale

  • Reduce sequence using function

  • Built-in

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

4.6.2. Syntax

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

4.6.4. Solution

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

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

4.6.6. Map Reduce

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

4.6.7. Assignments