Understanding Python's Filter Function
Ohidur Rahman Bappy
MAR 22, 2025
Understanding Python's Filter Function
The filter()
function evaluates each item in an iterable with a specified function that returns a boolean value. This can be particularly useful for processing lists.
Syntax
filter(function, iterable) --> filter object
The filter()
function takes two arguments: a function and a sequence (e.g., a list). Each item in the sequence is processed by the function, which returns True
or False
. Only those items that return True
are included in a filter object, which can be converted into a list, tuple, etc.
Prime Number Example
Consider the following isPrime()
function. This function returns True
if the input is a prime number, and False
otherwise. It is then used within filter()
to identify prime numbers in a range.
def isPrime(x):
for n in range(2, x):
if x % n == 0:
return False
return x > 1
fltrObj = filter(isPrime, range(10))
print('Prime numbers between 1-10:', list(fltrObj))
Output:
Prime numbers between 1-10: [2, 3, 5, 7]
Using Lambda with Filter
A lambda
function can also be utilized with filter()
. Below is an example that filters a list to include only even numbers.
fltrObj = filter(lambda x: x % 2 == 0, range(10))
print(list(fltrObj))
Output:
[0, 2, 4, 6, 8]
By using filter()
, we can efficiently process and extract data from sequences based on custom criteria.