The Python Filter function, as the name implies is used to filter through iterables or sequences such as lists, tuples and dictionaries.

Before calling the filter function however, you need to have an appropriate function created that will be used to test each element in the iterable to see if it qualifies or not. If it passes, it will be returned in the output, else not.


Syntax

The syntax for the Python filter function.

filter(function, iterable1 .......)

The first parameter is always the function which is to be applied on the iterable. There can be multiple iterables passed into the filter function as long as the function has the same number of parameters.

Example

In the example below, we’ll be using the following scenario.

We have the data of 10 students with us who have recently given an exam. We have to write code to determine whether they have passed this exam or not. The qualifying mark is 60. Those below 60 will fail.

def check(x):
     return x > 60

list1 = [98,67,21,52,84,78,11,7,99,60]
result = list(filter(check , list1)) 
print(result) 

All the numbers greater than 60 are now returned in a list. The filter function merely creates an object, hence why we used the list function.

[98, 67, 84, 78, 99]

If you want to improve on this code, you could create a dictionary instead of a list. This way, we would have both the names and the marks for a student who passed.


Bonus Example

A bonus example of the filter function being used with the anonymous lambda function.

list1 = [3,5,4,8,6,33,22,18,76,1] 
result = list(filter(lambda x: (x%2 != 0) , list1)) 
print(result) 

The function above returns True if the number is odd and False if it is even. Hence it returns all odd numbers.

[3, 5, 33, 1]

This marks the end of the Python Filter function article. Any suggestions or contributions for CodersLegacy are more than welcome. Relevant Questions can be asked in the comments section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments