Two approaches to filtering with filterfalse() and filter()

In Chapter 5, Higher-Order Functions, we looked at the built-in filter() function. The filterfalse() function from the itertools module could be defined from the filter() function, as follows:

filterfalse = (lambda pred, iterable:
    filter(lambda x: not pred(x), iterable)) 

As with the filter() function, the predicate function can be the None value. The value of the filter(None, iterable) method is all the True values in the iterable. The value of the filterfalse(None, iterable) method is all of the False values from the iterable:

>>> filter(None, [0, False, 1, 2])
>>> list(_)
[1, 2]
>>> filterfalse(None, [0, False, 1, 2]) <itertools.filterfalse object at 0x101b43a50> >>> list(_) [0, ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.