Filter in Python

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. 

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

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. 

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
  else:
      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 - 

ExamplesofFilter_1

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 - 

ExamplesofFilter_2

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:

   print(element)

Output - 

ExamplesofFilter_3

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.

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

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

   else:

       return False

filtered_object = filter(func, books)

for d in filtered_object:

   print(dict(d)["Title"])    

Output - 

ExamplesofFilter_4

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.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

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.

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!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.