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)
>>>
>>> print(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/idiom-reduce-mapreduce.gif

5.8.7. Assignments

Todo

Create assignments