logo

Selecting Data with filter()

filter() keeps only the items that pass a test (return True from a function).

numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # [2, 4, 6]

The function you provide is a predicate - it answers yes or no for each item. filter() collects the yeses.

Like map(), it returns an iterator. The original sequence is unchanged.

You can combine map() and filter():

# Square only the even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
squared = map(lambda x: x ** 2, evens)
print(list(squared))  # [4, 16, 36]

This pipeline approach - filter then transform - is central to functional data processing.

I cover filter patterns in my Functional Programming course.