8.17. Builtin Reduce
Reduce sequence using function
Built-in
>>> 1 + 2
3
>>> 1 + 2 + 3 + 4
10
8.17.1. Syntax
functools.reduce(function, iterable[, initializer])
required
callable
- Functionrequired
iterable
- Sequence or iterator object
8.17.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
8.17.3. Solution
>>> from functools import reduce
>>>
>>>
>>> def add(x, y):
... return x + y
>>>
>>>
>>> DATA = [1, 2, 3, 4]
>>>
>>> reduce(add, DATA)
10
8.17.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