Filter in Python: An Introduction to Filter() Function [with Examples]
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.
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 -

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:
print(element)
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.
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 -

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.