What is the itertools.filterfalse() method in Python?
Overview
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.
Syntax
filterfalse(predicate, iterable)
Parameters
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.
Example 1:
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)
Explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of numbers called
lstranging from0to9using therange()method. - Lines 5 to 6: We define a method called
is_evento check whether a given number is even or odd. - Line 8: We apply the
is_evenmethod onlstusing thefilterfalsemethod. The result is callednew_lst. - Line 10: We print
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.
Example 2
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)
Explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of numbers called
lstranging from0to9using therange()method. - Lines 5: We define a lambda function called
is_eventhat determines whether a given number is even or odd. - Line 7: We apply the
is_evenlambda function onlstusing thefilterfalsemethod. The result is callednew_lst. - Line 9: We print
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.