Filter Function in Python

Rina Mondal
1 min readApr 14, 2024

--

The filter() function is used to filter elements from an iterable (such as a list, tuple, or dictionary) based on a specified condition. It returns an iterator that yields the elements from the iterable for which the function returns True.

Here’s a basic example of how you might use filter() in Python:

# Define a function to check if a number is even
def is_even(x):
return x % 2 == 0

# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter() to keep only the even numbers from the list
even_numbers = filter(is_even, numbers)

# Convert the filter object to a list for printing
print(list(even_numbers))

# Output: [2, 4, 6, 8, 10]

In this example, the “is_even()” function is used with “filter()” to retain only the even numbers from the `numbers` list.

The result is a new iterable (in this case, a filter object) containing only the filtered elements.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.