How to Use the filter() Function in Python

Learn how to use Python's filter() function to extract elements from collections. Compare filter with list comprehensions and lambda callbacks.

Try Code in Editor

Explanation

Data filtering is a core task in application programming. You will often need to search through a list and extract elements that meet specific criteria, such as extracting active users from a profile database, or filtering out negative numbers from sensor logs. Python provides a built-in functional tool named `filter()` for this purpose.

The `filter(function, iterable)` function takes a filtering function and an iterable as arguments. The function argument must return a boolean value (`True` or `False`) for each element. The `filter()` function evaluates each element, retaining only those that evaluate to `True`, and returns an iterator object (a `filter` object) containing the results.

Like `map()`, `filter()` evaluates elements lazily. If you need a standard list immediately, you cast the output using the `list()` constructor: `list(filter(func, data))`. If you pass `None` as the function parameter (e.g., `filter(None, data)`), Python will automatically filter out all elements that are falsy, which is a great shorthand for clearing empty values.

Step-by-Step Implementation

  1. 1

    Define a function that accepts an element and returns a boolean value representing the filter criteria.

  2. 2

    Call filter(function, iterable) to create a lazy iterator of matches.

  3. 3

    Cast the resulting filter object to a list using list(filter(...)) if you need to manipulate the records.

  4. 4

    Pass None as the function argument to filter out all falsy values (like None, 0, and empty strings).

Code Example

This script demonstrates filtering numeric arrays, extracting dictionary items, and discarding falsy empty strings with filter().

filter_function.py
Try in Editor
numbers = [-5, -2, 0, 3, 8, -1]

# 1. Filter positive numbers using a lambda function
positives = list(filter(lambda x: x > 0, numbers))
print("Positives only:", positives)

# 2. Filter list of strings by character length
words = ["cat", "elephant", "dog", "giraffe"]
long_words = list(filter(lambda w: len(w) > 4, words))
print("Words longer than 4 chars:", long_words)

# 3. Shorthand: Remove all falsy values from a list by passing None
mixed_data = ["hello", "", "world", None, False, "active"]
clean_data = list(filter(None, mixed_data))
print("Falsy values removed:", clean_data)
Terminal Output
Positives only: [3, 8]
Words longer than 4 chars: ['elephant', 'giraffe']
Falsy values removed: ['hello', 'world', 'active']

Frequently Asked Questions

What happens if the function passed to filter() does not return a boolean?

Python evaluates the truthiness of the returned value. If the value evaluates to True in a boolean context, the element is kept.

Should I use filter() or a list comprehension?

A list comprehension with an if condition (e.g., [x for x in list if condition]) is often preferred for readability, but filter() is clean and highly performant, especially when using existing built-in functions.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.