filter(): filter an iterable based on a function in Python

The filter() function will filter an iterable based on a given function.

Dictionaries, lists, and tuples are examples of iterables.

The first argument is the function name, the second argument is the iterable.

Let’s filter to have only the numbers greater than 5.

def filter_greater_than_five(number):
    return number > 5

numbers = [2, 3, 4, 5, 10, 18, 32]

filtered_list = filter(filter_greater_than_five, numbers)

print(filtered_list)

print(list(filtered_list))
<filter object at 0x105669c40>

[10, 18, 32]

Notice that filter() returns a filter object, so you have to convert it to a list or tuple, for instance, to print the results.

I recommend learning about Python Lambda Functions to see filter() applied in another way.

Watch on Youtube

You can also watch this content on Youtube: