The builtin filter()
function filters out and returns the elements of an iterable that evaluates to True
when a particular function is applied on them. The itertools.filterfalse()
function serves the opposite purpose by filtering out and returning only those elements that evaluates to False
.
with filter()
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def is_odd(num):
return num % 2 == 1
odds = filter(is_odd, data)
print(*odds)
with filterfalse()
#import the filterfalse function
from itertools import filterfalse
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def is_odd(num):
return num % 2 == 1
evens = filterfalse(is_odd, data)
print(*evens)
As you can see in the above example, the two functions returns opposite results given the same function as key.
filterfalse(func, iterable)
func |
Required. The function to be used in filtering. If None is given as the argument, the elements will be filtered by their boolean values. |
iterable |
Required. The iterable object containing the elements to be filtered. |
The function returns an iterator object which returns only those items in the iterable
for which function(item)
evaluates to False
.
from itertools import filterfalse
data = [13, 2, 18, 20, 5, 15, 7, 11]
#get elements bigger than 10
result = filterfalse(lambda x: x < 10, data)
print(*result)