Python filter() Function


Python filter() Function

The filter() function applies the specified function to all the elements of the sequence and returns the element for which the function returns true.

After performing the operation, it returns the iterator/sequence as the result.

Syntax:

filter(function, iterable)

Parameters:

FunctionThis is the name of the function without parenthesis.
IterableAny sequence like list, tuple, etc

Example:

In [1]:
def even_numbers(n):
    if n % 2 == 0:
        return True
    else:
        return False
In [2]:
numbers = [1,2,3,4,5,6,7,8]

output = filter(even_numbers,numbers)

print(list(output))
[2, 4, 6, 8]

Processing Return value:

The map() function returns the object of the map class. We can process this data in two ways:

  1. Using a for loop to iterate through the return values.
  2. Using list(), tuple() functions to convert output to the list, tuple, etc.

1. Using a for loop to iterate through the return values.

In [1]:
def even_numbers(n):
    return n % 2 == 0
In [2]:
numbers = [1,2,3,4,5,6,7,8]

output = filter(even_numbers,numbers)

for num in output:
    print(num)
2
4
6
8

2. Using list(), tuple() functions to convert output to the list, tuple, etc.

In [1]:
def even_numbers(n):
    return n % 2 == 0
In [2]:
numbers = [1,2,3,4,5,6,7,8]

output = filter(even_numbers,numbers)

print(list(output))
[2, 4, 6, 8]

The filter() function with lambda

The filter function is commonly used with the lambda function. This is the most efficient use of the filter function. In this example, we will use the lambda function to filter out the odd numbers and the even numbers from the list.

In [1]:
numbers = [1,2,3,4,5,6,7,8,9]

odd_numbers = filter(lambda x: x%2 == 1, numbers)

print("Odd Numbers =",list(odd_numbers))

even_numbers = filter(lambda x: x%2 == 0, numbers)

print("Even Numbers =",list(even_numbers))
Odd Numbers = [1, 3, 5, 7, 9]
Even Numbers = [2, 4, 6, 8]

The filter() function with custom functions

The filter function can be used with the custom functions. In the below example, we are finding out the odd and even numbers, but this time we have created our own custom functions. These custom functions are called using the lambda function.

In [1]:
def even_numbers(num):
    return num%2 == 0

def odd_numbers(num):
    return num%2 == 1

numbers = [1,2,3,4,5,6,7,8,9]


odd = filter(lambda x: odd_numbers(x), numbers)

print("Odd Numbers =",list(odd))

even = filter(lambda x: even_numbers(x), numbers)

print("Even Numbers =",list(even))
Odd Numbers = [1, 3, 5, 7, 9]
Even Numbers = [2, 4, 6, 8]

Filter with None

The same filter() function can be used with the None also, when we use the filter function with the none, all the falsy values, which means the values that will return false will be removed.

In [1]:
my_list = [1,2,'a','b',0,'0','']

new_list  = filter(None, my_list)

print(list(new_list))
[1, 2, 'a', 'b', '0']

References:

  1. filter() in python
  2. Python filter() Function Guide