The filter() function in Python is a built-in function used to select elements from an iterable based on a specified condition. It applies a function to each element of an iterable and returns only those elements for which the function returns True.
In simple terms, filter() is used to remove unwanted elements from a sequence according to a condition.
The function returns a filter object (iterator) containing the filtered elements.
filter(function, iterable)
Parameters
function
A function that tests each element and returns either True or False.
iterable A sequence such as a list, tuple, or string whose elements are to be filtered.
Return Value
def even_number(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
result = filter(even_number, numbers)
print(list(result))
Output
[2, 4, 6]
Explanation
even_number() checks whether a number is even.filter() applies this function to each element of the list.True are included.filter() with a Lambda FunctionA lambda function can be used for short conditions.
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
Output
[2, 4, 6]
Explanation
filter() keeps only the numbers that satisfy the condition.numbers = [-5, 3, -2, 7, -1, 10]
result = filter(lambda x: x > 0, numbers)
print(list(result))
Output
[3, 7, 10]
Explanation
words = ["apple", "", "banana", "", "cherry"]
result = filter(None, words)
print(list(result))
Output
['apple', 'banana', 'cherry']
Explanation
None removes empty values from the list.filter() vs With filter()Without filter()
numbers = [1, 2, 3, 4, 5]
result = []
for n in numbers:
if n % 2 == 0:
result.append(n)
print(result)
With filter()
numbers = [1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
Advantage
filter() makes the code shorter and more readable.filter() returns a filter object, not a list.list().Example:
result = filter(lambda x: x > 3, [1, 2, 3, 4, 5])
print(list(result))
Output:
[4, 5]
filter() is a built-in Python function used to filter elements from an iterable.