How To Use Reduce Function In Python

--

The aim of this pagešis to document the `reduce()` from the standard `functools` Python library. Reduce is a standard technique within functional programming - in other languages, it is known as `fold` or `accumulate` and typically combined with `map` and `filter` as brilliantly illustrated by prof. Abelson in the SICP Lecture on Streams.

1. DEFINE

• Repeatedly applies a function of two arguments to an interim accumulator value
• Each element of the series, in turn, updating (accumulating) the interim value with the result of the called function
• The initial value can be the first element in the input or an optional argument
• The final accumulated ā or reduced value is returned

2. EXAMPLE: SUMMATION OF A SEQUENCE

`from functools import reduceimport operatorreduce(operator.add, [1, 2, 3, 4, 5])numbers = [1, 2, 3, 4, 5]accumulator = operator.add(numbers[0], numbers[1])for item in numbers[2:]:    accumulator = operator.add(accumulator, item)print(accumulator)>>> 15`

3. PRINTING OUT REDUCTION

`def mul(x, y):    print(f"mul {x} {y}")    return x * yreduce(mul, range(1, 10))""" >>> reduce(mul, range(1, 10))mul 1 2mul 2 3mul 6 4mul 24 5mul 120 6mul 720 7mul 5040 8mul 40320 9362880 """`

4. EMPTY SEQUENCE RAISES A TYPE ERROR

• I am using the `mul` function defined above
`>>> reduce(mul, [])Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: reduce() of empty sequence with no initial value`

5. SINGLE-ITEM ELEMENTS NEVER CALL REDUCE

`>>> reduce(mul, [1])1`

6. OPTIONAL: INITIAL VALUE ARG

• this value is conceptually added to the beginning of the input sequence
• it, therefore, serves as the first accumulator value
• this means it is returned if the input sequence is empty
• useful if not sure that the input will have any values
`>>> import operator>>> values = [1,2,3]>>> reduce(operator.add, values, 0)6`
• take care when selecting the initial value ā the correct value depends on the function you are applying
• i.e. do not take initial value `0` for multiplication :)
`>>> values = [1,2,3]>>> reduce(mul, values, 0)mul 0 1mul 0 2mul 0 30>>> reduce(mul, values, 1)mul 1 1mul 1 2mul 2 36`