Python filter() function

Python’s filter() function is used to filter the elements of an iterable (sequence) with the help of a predicate that tests each element on the iterable.

A predicate is a function that always returns True or False. We cannot use a generic function with filter(), since it returns all elements only if a suitable condition is met. This means that the filtering function must always return a boolean value, and thus, the filter function is a predicate.


Basic Format of filter()

Since this is a function that operates on a Python iterable, the iterable is one of the parameters. And since it tests a predicate on each element, the function is also another parameter which is required.

And since it filters out elements from the sequence, it must also return an iterable, which only consists of the elements which satisfy the filtering function.

But in this case, since we work with objects, Python returns us a filter object as an iterable, which will prove to be handy for conversion to other types, using methods like list() and dict().

Simple, isn’t it? Let us look at how we apply this and create working programs using filter().

Format: filter_object = filter(predicate, iterable)

Here is a very simple example that filters a list with a function that tests whether a number is odd or even.

a = [1, 2, 3, 4, 5]

# We filter using a lambda function predicate.
# This predicate returns true
# only if the number is even.
filter_obj_even = filter(lambda x: x%2 == 0, a)

print(type(filter_obj_even))

# Convert to a list using list()
print('Even numbers:', list(filter_obj_even))

# We can also use define the predicate using def()
def odd(num):
    return (num % 2) != 0

filter_obj_odd = filter(odd, a)
print('Odd numbers:', list(filter_obj_odd))

Output

<class 'filter'>
Even numbers: [2, 4]
Odd numbers: [1, 3, 5]

Note that we can get the individual elements of the filter object by iterating through it, since it is an iterable:

for item in filter_obj_odd:
    print(item)

Output

1
3
5

filter() and None

We can also use None as a predicate with filter(). None returns True if the object has a boolean value of True, and False otherwise.

This means that objects like 0, None, '', [] etc, are all filtered out by None predicate, since they are empty element objects.

a = [0, 1, 'Hello', '', [], [1,2,3], 0.1, 0.0]

print(list(filter(None, a)))

Output

[1, 'Hello', [1, 2, 3], 0.1]

Conclusion

We learned about the filter() function that Python provides us with, for applying a predicate on an iterable.

The conciseness and readability of filter makes it a very popular function amongst Developers for modern Python codebases.


References