Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.filterfalse() Function



The Pythonitertools.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 fromiterable wherepredicate evaluates to False.

Example 1

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

import itertoolsdef is_even(n):   return n % 2 == 0numbers = [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 −

1357

Example 2

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

import itertoolsdef 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 −

applecherryelderberry

Example 3

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

import itertoolsdef is_negative(t):   return t[0] < 0data = [(-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 itertoolsdef 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 −

helloworldpython
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp