Combine filter() and reduce()
This means that in order to use it, you’ll have to import it from the
functools module. The
functools module in Python is a built-in module that provides higher-order functions and utilities to enhance the functionality of functions and callable objects.
reduce() takes in three arguments:
initial. By the way, the reason that
reduce() is considered as a higher-order function is that it takes in another function as one of its arguments, just like
The function argument represents the operation or calculation that will be applied to the elements of the iterable. The
iterable argument is the collection of elements that will be iterated over and reduced to a single value.
It can be a list, tuple, or any iterable object. The
initial value argument provides an optional starting value for the reduction. If provided, the function is first applied to this initial value and the first element of the sequence. If you leave it empty, the first element of the sequence is used as the initial value.
In this example, you’ll filter the odd numbers of a list using
filter(), and then you’ll use
reduce() to add all the even numbers and return a single value as the result. You’ll need to import
from functools import reduce.
Now it’s time to filter odd numbers from this list. You’ve already done this multiple times. You’ll need a predicate function,
is_even, that checks the remainder of a number when divided by
number as an input,
return number % 2 == 0.
Let’s check the even numbers. You got
50, so you have successfully filtered odd numbers. Perfect. Now that you have your even numbers, it’s time to use
reduce() to add them all together.
Then it applied the lambda function that you created on them.
6 is equal to
16, so the first cumulative result, which is called an accumulator, is
16 is going to be added to the next element, which is
66, and since there are no more elements,
reduce() returns a single value of
66, which is the sum up all the numbers in
You can turn this into a one-liner. Instead of creating a new list, like
even_numbers, you can directly use
filter() as reduce’s iterable argument because, as you know,
filter() returns an iterator.
Let’s keep everything the same, but instead of using
even_numbers, let’s use
b as input numbers, returning
a + b, and
filter() as reduce’s function argument.
Let’s put in
numbers as the iterable. Let’s see if you get
66 again. And you do. To recap,
filter() extracted the even numbers of the
numbers list and returned an iterator. You’re using that iterator directly as reduce’s iterable argument.
By the way, you may have noticed unlike
map(), where you needed to call the
list() function on the result, you don’t need to do that here since what you get is a single value, not an iterator.
Become a Member to join the conversation.