Python – Filter Function

Created with Sketch.

Python – Filter Function

The filter() function calls the specified function which returns boolen for each item of the specified iterable (list).

filter() Signature:
filter(function, iterable) --> filter object

 

The filter() function also receives two arguments, a function and a sequence (e.g. a list).
Each item in the list is processed by the function which returns True or False. Only those items which return True are stored in a filter object.
This can then be conveniently converted into a sequence.

Look at the following function isPrime() which returns True if the parameter is a prime number, otherwise it returns False.
This function is used inside filter() along with a range object producing numbers between 2 and 100. Only prime numbers are collected in the resulting list object.

def isPrime(x):
    for n in range(2,x):
        if x%n==0:
            return False
        else:
            return True

fltrObj=filter(isPrime, range(10))
print ('Prime numbers between 1-10:', list(fltrObj))

 

Result:
Prime numbers between 1-10: [3, 5, 7, 9]

 

The lambda function can also be used as a filter. The following program returns a list of even numbers from a range.

Example: Filter with Lambda Expression
fltrObj=filter(lambda x: x%2==0, range(10))
print(list(fltrObj))

 

Leave a Reply

Your email address will not be published. Required fields are marked *