The Python filter() Function

Introduction

The Python filter() function provides an elegant way to filter elements from an iterable based on a specified condition. It is a built-in function that works by applying a given function to each element of the iterable, and selecting only those elements for which the function returns True.

The filter() function is often used as an alternative to list comprehensions or loops when the goal is to extract specific elements from an iterable. It can lead to more readable and concise code, especially when dealing with complex filtering conditions. A list comprehension, however, is likely to have faster processing time.

Basic Python filter() Function Syntax

The basic syntax of the filter() function involves passing a function (which can also be a lambda expression) and an iterable as arguments. The function receives a single argument, which is an item from the iterable, and should return a boolean True or False value. It will be applied to each element of the iterable by filter(), which then returns an iterator containing only the elements for which the function returns True.

The following is the filter() syntax:

filter(function, iterable)
  • function: The function to test each element of the iterable.
  • iterable: The iterable whose elements will be filtered based on the condition specified by the function.

The following example demonstrates how to use filter() to extract even numbers from a list.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))

Output:

[2, 4, 6, 8, 10]

In this example:

  • lambda x: x % 2 == 0: The lambda function that checks whether a given number is even using the % modulus (remainder upon division) operator.
  • numbers: The original list of numbers.
  • filter(lambda x: x % 2 == 0, numbers): Filters the elements of the list, returning only those for which the lambda function returns True.

Note that just like the map() function, filter() returns an iterable, which then must be converted to a collection object such as a list in order to be printed out in a meaningful way.

The Filtering Process

Let’s take a closer look at how the filtering process of the filter() function works by replacing the lambda expression in the last example with an equivalent function that also prints out its argument and return value.

Example:

def is_even(x):
    return_value = x % 2 == 0
    print(f"Testing: {x}  Result: {return_value}")
    return return_value

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))

Output:

Testing: 1  Result: False
Testing: 2  Result: True
Testing: 3  Result: False
Testing: 4  Result: True
Testing: 5  Result: False
Testing: 6  Result: True
Testing: 7  Result: False
Testing: 8  Result: True
Testing: 9  Result: False
Testing: 10  Result: True
[2, 4, 6, 8, 10]

As you can see in the output, the function is_even() is called for each element in the iterable. For each element, it prints the testing message and returns True or False based on whether the element is even or not. The elements for which the function returns True are included in the final result.

Using filter() with None as the Function

One interesting feature of the filter() function is that if the function argument is set to None, it simply returns the elements of the iterable that are considered truthy. This can be useful in scenarios where you want to filter out elements with falsy values.

In Python, every value (including all objects) has a boolean equivalent. The values with a True boolean equivalent are considered “truthy” and those with False are considered “falsey”. Falsy values are typically those considered empty or void in some way such as “”, [], None, and 0. All the rest are “truthy”.

Example:

values = [0, 1, "", "hello", None, True, False]
truthy_values = filter(None, values)
print(list(truthy_values))

Output:

[1, 'hello', True]

In the example above, the filter() function, with None as the function argument, filters out elements that are considered falsy, returning only truthy values.

Summary & Reference for the Python filter() Function

The filter() function selectively extracts elements from an iterable based on a specified condition, returning an iterator containing only the elements for which the condition is True.


filter() is a built-in function and does not require importing any modules.


The basic filter() function syntax involves passing a function and an iterable: filter(function, iterable)

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x

: x % 2 == 0, numbers)  # even_numbers --> [2, 4, 6, 8, 10]

The function passed to filter() tests each element of the iterable. It should return True or False based on the specified condition.

def is_even(x):
    return x % 2 == 0

If the function argument is set to None, filter() returns truthy elements of the iterable.

values = [0, 1, "", "hello", None, True, False]
truthy_values = filter(None, values)  # truthy_values --> [1, 'hello', True]