All three higher-level functions we know are build-in in Python. However, map
and filter
are ready to use, and reduce
must be imported from the functools
module. Now, we will discuss the differences between each specific function and the simple options we implemented earlier.
The functools.reduce
function
Looking at the function declaration, we see:
reduce(function, sequence[, initial]) -> value
Here it is worth paying attention to the fact that the initial value of the accumulator is an optional argument [, initial]
. If it is not specified, then reduce
will use the first element of the sequence
as the initial value. In this case, we remember that the reduce
call will result in an error if the sequence is empty.
Let us observe an example of the functools.reduce
function:
from functools import reduce
numbers = [2, 3, 8]
def get_maximum(first_num, second_num):
return first_num if first_num > second_num else second_num
reduce(get_maximum, numbers, 10) # 10
reduce(get_maximum, numbers, 4) # 8
The filter
function
Now let us take a look at filter
:
filter(function or None, iterable) -> filter object
Here is the code:
numbers = [2, 3, 8, 15, 34, 42]
def is_even(num):