Python filter() function


Gaming Laptop Series

The filter function in Python filters the elements from a sequence or iterable with the use of a function that is passed as an argument to filter function. It tests each element that if it satisfies a certain condition or not.

Like the Python map() function, the filter() function also takes two arguments. The first argument is the function and the second is a sequence or iterable. In this article, you will learn how to use the filter() function in Python.

The syntax of the Python filter() function

The syntax of using the filter() function in Python is given below –

filter(func, iter)

Where,

func is the function that test if each element of iterable are true or not

iter is iterable that is need to be filtered using the func it can be a list, tuple, sets, etc

Example and usage of Python filter() function

In our example of using the filter() function,  we will filter the numbers that are divisible by 5 and store them in a list. We will create a Python program with a function that will check if each element of the given iterable is divisible by 5 or not and a list containing some numbers.

The filter function will return the filter object that we will convert into a list using the list() function. Now see the example which is given below –

numbers = [2,5,9,7,15,25,0,4,10]
def is_divisible(a):
       return a%5==0
numbers_updated= list(filter(is_divisible, numbers))
print(numbers_updated)

You can see the output of this in the given image –

You can modify the above program and can reduce the number of lines in the code by using the lambda expression.

numbers = [2,5,9,7,15,25,0,4,10]
numbers_updated= list(filter(lambda a:a%5==0, numbers))
print(numbers_updated)

When you execute this program it will produce the same result as the above program does. You can see the output of the printed list which contains all the numbers that are divisible by 5.

Now I hope you understand how to use the filter() function in your Python code. If you have a query on this topic then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.