Python filter() Function

Python filter() Function

The Python filter() function is another built-in function that is helpful when working with data. The filter() function actually accepts a function as an input, in addition to a sequence as input, and returns an iterator constructed from the items of the given sequence, for which the given function returns true. If you want to collect everything that lies in the result at the same time, you can call the list() function on the iterator that filter yields.

filter() with Lambda

We recently learned about lambda functions in Python, and they are very commonly used with the filter() function we are discussing here. Let’s see an example in action by looking at a list of numbers and filtering only the even numbers.

# Python Program to find even numbers
# from a list using an anonymous function

# Take a list of numbers.
list_of_ints = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# use anonymous lambda function to filter
result = list(filter(lambda x: (x % 2 == 0), list_of_ints))

# printing the result
[2, 4, 6, 8]

Example Two of filter and lambda

This next example looks at a list of strings. Some of the strings contained are a palindrome. This means that they are spelled the same in reverse as they are normally. We can use filter() with a lambda function to find only the palindromes in the list.

# Python Program to find palindromes in a list of strings.

list_of_strings = ['ferrari', 'racecar', 'tesla', 'level', 'technoking']

# use an anonymous function to filter palindromes.
result = list(filter(lambda x: (x == ''.join(reversed(x))), list_of_strings))

# print the palindromes
['racecar', 'level']

Custom Function With filter()

We can also use the standard def keyword in Python to define a function that has a name, then use that named function in combination with the filter() function. Here we’ll create a function that can filter odd numbers from a list.

# list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

# function that finds odd numbers
def is_odd(num):
    if (num % 2) != 0:
        return True
        return False

results = filter(is_odd, numbers)
[1, 3, 5, 7, 9, 11]

Removing Duplicates Using filter()

meats1 = ['steak', 'chicken', 'pork', 'bacon', 'ground beef']
meats2 = ['sausage', 'pork', 'duck', 'lamb', 'steak']

# function that filters duplicate string
def filterDuplicate(string_to_check):
    if string_to_check in the_list:
        return False
        return True

# Using filter() to remove duplicate strings
the_list = meats2
results = list(filter(filterDuplicate, meats1))
the_list = meats1
results += list(filter(filterDuplicate, meats2))

print("Duplicates removed: ", results)
Duplicates removed:  ['chicken', 'bacon', 'ground beef', 'sausage', 'duck', 'lamb']

filter() checks for True values

A key concept to understand with the filter() function is that it is checking for a True condition. Only values that are True can pass the filter. We can demonstrate this by passing the Python None value as the function to filter(), and the function will still work. Let’s see that concept here.

# list of values
list_of_values = ['1', 2, 0, False, True, '1', [], {}]

filtered_list = filter(None, list_of_values)

print('The filtered elements are:')
for element in filtered_list:
The filtered elements are:

Using filter() with a Dict

So far we have seen a few examples of how to use filter() with various lists. We can also use the filter() function with dictionaries in Python.

dictOfNames = {
    0: 'Rick',
    1: 'Vick',
    2: 'Bob',
    3: 'Rob',
    4: 'Soham',
    5: 'Dave'

# Filter dictionary by keeping elements whose values contain
# the letter 'a'
newDict = dict(filter(lambda elem: 'a' in elem[1], dictOfNames.items()))
print('Filtered Dictionary : ')
Filtered Dictionary : 
{4: 'Soham', 5: 'Dave'}

Python filter() Function Summary

The filter() function constructs an iterator from elements of an iterable for which a function returns true. The way this works is the filter() method filters the given iterable with the help of a function that tests each element in the iterable to be true or not.

The syntax of the filter() function is as follows:

filter(function, iterable)

The parameters for filter() are function and iterable.

  • function – function that tests if elements of an iterable return true or false
    If None, the function defaults to Identity function – which returns false if any elements are false
  • iterable – iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators

The filter() function returns an iterator that passed the function check for each element in the iterable.

The syntax of the filter() function when using a lambda is as follows:

filter(lambda item: item[] expression, iterable)