Last Updated : 11 Dec, 2024
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:
Example Usage of filter() Python
# Function to check if a number is even
def even(n):
return n % 2 == 0
a = [1, 2, 3, 4, 5, 6]
b = filter(even, a)
# Convert filter object to a list
print(list(b))
Explanation:
Let's explore filter() in detail:
Python filter() SyntaxThe filter() method in Python has the following syntax:
Syntax: filter(function, sequence)
The result is a filter object, which can be converted into a list, tuple or another iterable type.
Let us see a few examples of the filter() function in Python.
Using filter() with lambdaFor concise conditions, we can use a lambda function instead of defining a named function.
Python
a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)
print(list(b))
Here, the lambda function replaces even and directly defines the condition x % 2 == 0 inline.
Combining filter() with Other FunctionsWe can combine filter() with other Python functions like map() or use it in a pipeline to process data efficiently.
Example: Filtering and Transforming Data
Python
a = [1, 2, 3, 4, 5, 6]
# First, filter even numbers
b = filter(lambda x: x % 2 == 0, a)
# Then, double the filtered numbers
c = map(lambda x: x * 2, b)
print(list(c))
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4