The filter function in Python is used to fetch some selected elements from a iterable using certain conditions. In this article we will take a list and choose some elements from it by applying certain condition.
Syntax
filter(function, iterable) function: A Function to be run for each item in the iterable iterable: The iterable to be filtered
In the below example we define a function which will divide a number with 2 to check for any reminder and then decide if the number is odd or even. This function is applied to a list using filter().
Example
listA = [15, 8, 21, 13, 32] def findeven(x): if x %2 !=0: return False else: return True evenum = filter(findeven, listA) for x in evenum: print(x)
Output
Running the above code gives us the following result −
8 32