Python itertools.filterfalse() Function



The Python itertools.filterfalse() function is used to filter elements from an iterable by removing those that satisfy a given predicate function. It returns only those elements for which the predicate evaluates to False.

This function is useful when you need to exclude specific elements based on a condition.

Syntax

Following is the syntax of the Python itertools.filterfalse() function −

itertools.filterfalse(predicate, iterable)

Parameters

This function accepts the following parameters −

  • predicate: A function that returns True or False. Elements are included only if the function returns False.
  • iterable: The iterable to be processed.

Return Value

This function returns an iterator containing elements from iterable where predicate evaluates to False.

Example 1

Following is an example of the Python itertools.filterfalse() function. Here, we remove even numbers from the list −

import itertools

def is_even(n):
   return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = itertools.filterfalse(is_even, numbers)
for num in result:
   print(num)

Following is the output of the above code −

1
3
5
7

Example 2

Here, we use itertools.filterfalse() function to filter out words that start with an uppercase letter −

import itertools

def starts_with_upper(s):
   return s[0].isupper()

words = ["apple", "Banana", "cherry", "Date", "elderberry"]
filtered_words = itertools.filterfalse(starts_with_upper, words)
for word in filtered_words:
   print(word)

Output of the above code is as follows −

apple
cherry
elderberry

Example 3

Now, we use itertools.filterfalse() function to remove tuples where the first element is negative −

import itertools

def is_negative(t):
   return t[0] < 0

data = [(-2, "A"), (-1, "B"), (0, "C"), (1, "D"), (2, "E")]
result = itertools.filterfalse(is_negative, data)
for item in result:
   print(item)

The result obtained is as shown below −

(0, "C")
(1, "D")
(2, "E")

Example 4

We can use itertools.filterfalse() function to remove empty strings from a list of words −

import itertools

def is_empty(s):
   return s == ""

words = ["hello", "", "world", "", "python", ""]
filtered_words = itertools.filterfalse(is_empty, words)
for word in filtered_words:
   print(word)

The result produced is as follows −

hello
world
python
python_modules.htm
Advertisements