In Python, filter() is a built-in function that applies a given function to each element of an iterable and returns a new iterable containing only the elements that satisfy the condition.
Function Syntax
filter(function, iterable)
Parameters:
function: A specified function that takes one parameter and returns a boolean value.This function determines whether each element in the iterable meets the condition. If the function returns
True, the element is included in the iterable returned byfilter(); if it returnsFalse, the element is excluded.iterable: An iterable object such as a list, tuple, or set.
filter() returns an iterable object containing only the elements that satisfy the condition.
filter() Function Examples
Suppose we need to filter even numbers from a list. We can use the filter() function:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(number):
return number % 2 == 0
even_numbers = list(filter(is_even, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]