Introduction to Filter in Python

Filter() is a built-in function in Python. The filter function can be applied to an iterable such as a list or a dictionary and create a new iterator. This new iterator can filter out certain specific elements based on the condition that you provide very efficiently. 

Note: An iterable in Python is an object that you can iterate over. It is possible to loop over an iterable and return items that are in it.

There are many ways to filter elements from a list. This includes using a simple for loop, list comprehension, advanced for loop, etc. However, the filter method provides a simple and efficient way to filter out elements and even takes fewer lines of code to carry out the same function. This is very useful especially when you are working with large sets of data. 

Consider this simple scenario. Suppose, you have a list of books that contains details of more than 1000 books. Now, if you try to use a comprehensive function to filter out specific books, the process can be quite exhaustive in terms of resource utilization. The comprehensive list will create a new list and by the time it has completed its entire operation, you will have two lists in our memory. And when the lists are very large, this can cause a huge problem. Moreover, it increases the overall runtime of the processing. 

In contrast to this, the filter() function will simply make an object which will not be a copy of the list but will be a reference to the original list, along with the function that has been provided to filter, and the indices which have to be traversed in the original list. Needless to say, this takes less memory and executes faster than list comprehension. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The Syntax For Filter in Python

The syntax for the filter() function in Python is - 

filter(function, iterable)

The two parameters are the following - 

  1. Function - It works on each element of the iterable and tests whether the returned value is true or false. The output sequence will contain all those elements of the iterable for which the function has returned True. It can also be mentioned as None. In such a case, the output sequence will simply contain all those elements that satisfy the boolean condition True.
  2. Iterable - It is the iterable or the list of items on which the filtering is to be performed on. An iterable can be a set, list, tuple, dictionary, etc.

The filter() method in Python will return an iterator that will contain all the elements of the original iterable that has passed the function check.

Also Read: The Basics of Python Loops

Applications of Filter in Python

The filter() method in Python can be used for a variety of purposes. It is the perfect replacement of list comprehension in terms of memory and execution time. The filter function can be used along with lambda functions to separate or filter elements based on the function check. In fact, instead of a lambda function, you can also use a normal/traditional function as well. 

For example, if you want to filter out the odd and even elements from a list of numbers into two different sets, you can use the filter function. You can even use it with a list of dictionaries to filter out dictionaries based on their keys. 

Examples of Filter in Python

Now, check out a few examples which will demonstrate the different ways in which you can use the filter method in Python. You can try out this method on different iterables using a lambda function, a traditional function, and without specifying a function.

Example 1. Using Filter With a Simple Function on a List.

Suppose you have a list of letters and we want to filter out the vowels using a filter on that list. You can create a simple function to check whether a letter as an argument to that function is a vowel or not and return True or False based on the check. It is also possible to use this method as an argument for the filter function along with the list of letters. Now, try it out.

Program - 

def check(letter):
  list_of_vowels = ['a', 'e', 'i', 'o', 'u']
  if letter in list_of_vowels:
      return True
      return False
letters = ['u', 'a', 'q', 'c', 'i', 'd', 'z', 'p', 'e']
filtered_object = filter(check, letters)
print("The type of returned object is: ", type(filtered_object))
filtered_list = list(filtered_object)
print("The list of vowels is: ", filtered_list)

Output - 


Example 2. Using Filter With a Lambda Function on a List

In this example, you will use the filter function on a list of numbers to separate the numbers into two lists of odd and even numbers. Here, use the lambda function instead of a traditional function in the parameter.

Program - 

nums = [5, 10, 23, 64, 42, 53, 93, 2, 0, -14, 6, -22, -13]

#Filter all the odd numbers from the list

odd = filter(lambda p : p%2 != 0, nums)

#Filter all the even numbers from the list

even = filter(lambda p: p%2 == 0, nums)

print("The list of odd numbers is: ", list(odd))

print("The list of even numbers is: ", list(even))

Output - 


Example 3. Using Filter With None as a Function Parameter

If you use the None as a function argument, the filter method will remove any element from the iterable that it considers to be false. Some examples of such elements are empty strings, 0, empty braces, boolean False, etc. Let’s check out the below example.

Program - 

my_list = [5, -23, "", True, False, 0, 0.0, {}, []]

filtered_object = filter(None, my_list)

for element in filtered_object:


Output - 


Explanation - 

The filter function has returned only those elements that it considers to be true. In this example, all the falsy elements such as empty braces, 0 values, empty strings, etc. would return false. Hence, they are not filtered out.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 4. Using Filter With a List of Dictionaries

In this example, you will create a list of dictionaries that will store details of books such as author names, publication, price, etc. The aim is to try to filter out the details of those books that are costlier than a fixed price. Let’s check out the example below.

Program - 

books = [

   {"Title":"Angels and Demons", "Author":"Dan Brown", "Price":500},

   {"Title":"Gone Girl", "Author":"Gillian Flynn", "Price":730},

   {"Title":"The Silent Patient", "Author":"Alex Michaelidis", "Price":945},

   {"Title":"Before I Go To Sleep", "Author":"S.J Watson", "Price":400}


def func(book):

   if book["Price"] > 500:

       return True


       return False

filtered_object = filter(func, books)

for d in filtered_object:


Output - 


Explanation - 

In the above program, you have created a list of dictionaries that contains details of books such as title, author, price, etc. You have also defined a function that takes as an argument a dictionary and returns True if the price of the book in that dictionary is greater than 500, else False. Then, you used a filter on the list of dictionaries using the function that was defined previously. The returned filter object has been iterated to print only the title of those books returned by the filter. As it is evident, only those titles have been returned whose price is greater than 500.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Wrapping Up!

In this detailed guide on filter in Python, you looked into the basics of the filter method which is used to filter elements from an iterable based on a function. This article also discussed some typical applications of the filter method along with the syntax and the parameters. Then, you moved forward and explored some useful examples where one would use the filter method with lambda functions, custom functions, and even with None option on different iterables like lists, list of dictionaries, etc.

If you are looking for the most effective way to this tech industry of web development, a great way to start would be to enroll in the comprehensive Python Training Course. With this course, you will gain all the practical and work-ready skills you’d need to be employable and grab the best opportunities for you in the field. 

Hope that you now have hands-on experience working with the Filter method in Python. Do you have any questions for us? Leave them in the comments section of this article, and our experts will answer them for you at the earliest!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Automation Test Engineer

Cohort Starts: 29 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 4 Jun, 2024

6 Months$ 1,449
Full Stack Developer - MERN Stack

Cohort Starts: 18 Jun, 2024

6 Months$ 1,449