Python filter() function is used to remove or filter out some items from an iterable based on a condition.

filter() accepts two arguments and returns another iterable which contains the elements which were not filtered or which satisfied the condition.

filter() syntax
Syntax of filter() function is

iterable = filter(function, iterable)

filter() accepts two arguments.
1. A function which returns True or False.
2. An iterable. This iterable may be a string, list, set or a tuple.

Function given as argument to filter() is invoked for each element of iterable.
If the function returns True, this element is included in the result otherwise it is ignored.

filter() returns an object of class filter which is an iterable.
filter() example
Suppose there is a list of numbers and you want to create a new list from the first list having only those numbers which are greater than 0.
Python code without filter() would be

# list of numbers
numbers = [10,-2, 57, -9, 12,-34]
# list of positive numbers
positive = []
# iterate over list
for num in numbers:
    # check if number is greater than 0   
    if num >= 0:
        positive.append(num)

print('Original list:', numbers)
print('Numbers greater than 0:', positive)

This prints

Original list: [10, -2, 57, -9, 12, -34] Numbers greater than 0: [10, 57, 12]

Above example can be modified to use filter() function as below

def check_positive(num):
   return num >= 0

# list of numbers
numbers = [10,-2, 57, -9, 12,-34]
filtered_object = filter(check_positive, numbers)
# list of positive numbers
positive = list(filtered_object)

print('Original list:', numbers)
print('Numbers greater than 0:', positive)

Explanation
Above code defines a function check_positive which returns True or False as the argument it receives is greater than or lesser than 0 respectively.
This function is supplied to filter() as the first argument. Second argument to filter() is a list of numbers.

For each element of the list check_positive is invoked. If this function returns True, the corresponding element is added to the result otherwise not.
Note that there are no parenthesis around function name in filter() and each list element is sent to the function implicitly.

filter() returns an object of class filter which is then passed on to list constructor to create a new list.

Instead of assigning filter() result to a new variable, it can be directly supplied to list constructor as

positive = list(filter(check_positive, numbers))

Filter with lambda function
Lambda functions are functions without a name also referred as anonymous functions. Lambda functions are defined at the location where they are required using lambda keyword.
As we saw above, filter() accepts a function as argument. Instead of creating a separate function, we can write it as a lambda function.
Thus, above example can be modified as

# list of numbers
numbers = [10,-2, 57, -9, 12,-34]
filtered_object = filter(lambda num: num >= 0, numbers)
# list of positive numbers
positive = list(filtered_object)

print('Original list:', numbers)
print('Numbers greater than 0:', positive)

This will get the same result. Notice how filter() is used with a lambda function.
filter() without argument function
filter() function can also be called without the argument function or writing None in place of argument function.
If None is used as argument function, it is called Identity function and in that case, values which result in True are added to the result.
Example,

numbers = [10, -2, 57, -9, 12,-34, 1, 0]
filtered_object = filter(None, numbers)
# list of positive numbers
positive = list(filtered_object)

print('Original list:', numbers)
print('Numbers greater than 0:', positive)

This prints

Original list: [10, -2, 57, -9, 12, -34, 1, 0] Numbers greater than 0: [10, -2, 57, -9, 12, -34, 1]

Notice that 0 is removed from the result since it is considered as False. All other numbers and 1 are assumed to be True.
If the list contains a boolean False value, then it will also be removed by Identity function.

Hope this article was able to explain the usage of filter() function in python.

Leave a Reply