Filter Function in Python
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.