The filter()
function in Python is used to extract those items from an existing iterable that satisfies a given condition. For example, filtering all even numbers from a list of numbers, or filtering all positive numbers from the list of numbers, or any such kind of operation. This process is known as a filtering operation.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def is_even(num): if num % 2 == 0: return True even_numbers = filter(is_even, numbers) print(list(even_numbers)) # Output # [2, 4, 6, 8, 10]
Syntax of filter()
The syntax of the filter()
function is as follows:
filter(function, iterable)
Parameters of filter()
The filter()
function takes in two arguments:
- function – A filtering function that removes unwanted items from the sequence by putting some condition. It must be a single parameter function.
- iterable – A sequence of items on which the filtering opeation has to be preformed.
filter() Return Value
The filter()
function returns an iterator. This iterator contains only those items which satisfy the condition written inside the filtering function.
This iterator can later easily be converted to other iterable sequences like lists, sets, tuples, etc. based on your requirement.
Understanding Python filter() Function
Now that we have understood the basic syntax of the filter()
function. Let’s move on to its actual working with the help of some basic examples.
Suppose, we have a list of some positive numbers and we want to filter out only the even numbers from it without modifying the actual list. How would you do that? Well, the most common approach to do this is using a for loop. See the example below:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [] for num in numbers: if num % 2 == 0: even_numbers.append(num) print(even_numbers)
Output:
[2, 4, 6, 8, 10]
You can see from the above output that we got the desired result. But is it the only way to achieve this? Well, no. We can also achieve the same result using the filter()
function in a much easier way. So, let’s understand it in detail.
The filter()
function takes exactly two parameters. The first is the filtering function that helps us removing unwanted items from the list and considering only the desired ones. The second is a sequence of items on which the filtering operation is performed.
Just like the for loop, the filter()
function also iterates over each element of the given sequence and implicitly passes each item to the filtering function as its argument.
Now the filtering function checks whether the current item satisfies the given condition or not. If the current item matches the given condition, the filtering function returns a boolean value True. This sends a signal to the filter()
function that the current item should be considered as a part of the final output.
Otherwise, if the current item does not satisfy the given condition, it is excluded from the final result. See the implementation in the example below:
Example: Filter all even numbers from the list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def is_even(num): if num % 2 == 0: return True even_numbers = filter(is_even, numbers) print(list(even_numbers))
Output:
[2, 4, 6, 8, 10]
Python filter() with dictionary
Similar to the lists, we can also apply the filter()
function to filter out desired data from Python dictionaries. Here, the only thing we have to keep in mind is that the filter()
function passes only keys to the filtering function as an argument, not the key-value pair.
In the example below, we have a dictionary that contains the student’s name as a key, and the marks as its value. The task is to filter out all the students that have marks more than 75.
students = { 'John': 87.5, 'Alice': 62, 'Bob': 67.5, 'Carl': 75.9, 'Ann': 82, 'Liz': 78.4 } def is_applicable(key): if students[key] > 75: return True applicable_students = filter(is_applicable, students) print(list(applicable_students))
Output:
['John', 'Carl', 'Ann', 'Liz']
Python filter() with lambda Function
Similar to the map() function, we can also use the lambda function with the filter()
function. The working of the lambda function is similar to a regular function except that it does not have a return statement because its body is automatically returned.
The main advantage of the lambda function is that we have to write less code.
Example 1: Filter even numbers from the list using lambda function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = filter(lambda num: num%2 == 0, numbers) print(list(even_numbers))
Output:
[2, 4, 6, 8, 10]
Example 2: Filter students having marks more than 75% using the lambda function
students = { 'John': 87.5, 'Alice': 62, 'Bob': 67.5, 'Carl': 75.9, 'Ann': 82, 'Liz': 78.4 } applicable_students = filter(lambda key: students[key] > 75, students) print(list(applicable_students))
Output:
['John', 'Carl', 'Ann', 'Liz']
Using None as a Function with filter()
The first parameter of the filter()
function can also be None
. In this case, the filter function removes all the values from the sequence that evaluate to False
.
data = [1, False, True, None, 0, '', '0', '1'] truthy_values = filter(None, data) print(list(truthy_values))
Output:
[1, True, '0', '1']