Programming Languages

What is the purpose of the filter function in Python?

Easy
6
Added
The filter function constructs an iterator from elements of an iterable for which a function returns true.

Solution Code

Programming Languages
def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
Explanation
This code snippet demonstrates how to use the filter function to filter elements from a list.

Guided Hints

Define a function to filter by
Use filter to apply the function to the iterable
Convert the filter object to a list to see the results