In Python, itertools
is a module which provides functions that help to iterate through iterables
very quickly.
The filterfalse
method in the itertools
module accepts a predicate
and an iterable
. The method returns the elements of the iterable
for which the predicate
is False
. The method ignores the elements from the iterable
for which the predicate returns True
.
filterfalse(predicate, iterable)
predicate
: The predicate function accepts an input and returns a boolean value. It can be an in-built function, user-defined function, or a lambda function.iterable
: This is the list or string while this method is applied.We use a user-defined function as a predicate in the code below:
import itertoolslst = range(10)def is_even(x):return x % 2 == 0new_lst = list(itertools.filterfalse(is_even, lst))print(new_lst)
itertools
module.lst
ranging from 0
to 9
using the range()
method.is_even
to check whether a given number is even or odd.is_even
method on lst
using the filterfalse
method. The result is called new_lst
.new_lst
.The output consists of odd numbers from the given iterable because odd numbers result in a false
value when the is_even
predicate is applied to them.
We use the lambda function as a predicate in the code below:
import itertoolslst = range(10)is_even = lambda x:x%2==0new_lst = list(itertools.filterfalse(is_even, lst))print(new_lst)
itertools
module.lst
ranging from 0
to 9
using the range()
method.is_even
that determines whether a given number is even or odd.is_even
lambda function on lst
using the filterfalse
method. The result is called new_lst
.new_lst
.The output consists of odd numbers from the given iterable because odd numbers result in a false
value when the is_even
predicate is applied to them.