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 itertools
lst = range(10)
def is_even(x):
return x % 2 == 0
new_lst = list(itertools.filterfalse(is_even, lst))
print(new_lst)

Explanation

  • Line 1: We import the itertools module.
  • Line 3: We define an iterable of numbers called lst ranging from 0 to 9 using the range() method.
  • Lines 5 to 6: We define a method called is_even to check whether a given number is even or odd.
  • Line 8: We apply the is_even method on lst using the filterfalse method. The result is called new_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 itertools
lst = range(10)
is_even = lambda x:x%2==0
new_lst = list(itertools.filterfalse(is_even, lst))
print(new_lst)

Explanation

  • Line 1: We import the itertools module.
  • Line 3: We define an iterable of numbers called lst ranging from 0 to 9 using the range() method.
  • Lines 5: We define a lambda function called is_even that determines whether a given number is even or odd.
  • Line 7: We apply the is_even lambda function on lst using the filterfalse method. The result is called new_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.

Free Resources