filter()
The built-in filter() function in Python is used to process an iterable and extract items that satisfy a given condition, as determined by a filtering function.
filter() returns an iterator that yields only the elements for which the filtering function returns a truthy value:
>>> numbers = [-2, -1, 0, 1, 2]
>>> positive_numbers = filter(lambda n: n > 0, numbers)
>>> list(positive_numbers)
[1, 2]
Choose a function argument below to see how filter() tests each item in numbers and keeps only the items that get a truthy result:
Each row shows an item from numbers, what the selected function returns for it, and whether filter() yielded or skipped it. Green marks a truthy return value and red marks a falsy one. Click Replay to watch filter() check the items one at a time, with the current item highlighted in yellow, while the Result list fills in.
Switch to is_even and notice that 0 is yielded even though it’s falsy, because only the function’s return value counts. With None, there’s no function to call, so each item’s own truthiness decides, and only 0 is skipped.
filter() Signature
filter(function, iterable, /)
Arguments
Return Value
- A
filterobject that yields elements from the input iterable that satisfy the filtering condition checked byfunction.
Note: If function is None, then the identity function is assumed and all the falsy elements in iterable are skipped.
filter() Examples
With a custom function and a list of numbers as arguments:
>>> def is_even(number):
... return number % 2 == 0
...
>>> list(filter(is_even, [1, 3, 10, 45, 6, 50]))
[10, 6, 50]
With a lambda function and a list of numbers as arguments:
>>> list(filter(lambda number: number % 2 == 0, [1, 3, 10, 45, 6, 50]))
[10, 6, 50]
With None as the function argument:
>>> truthy_objects = filter(None, [0, 1, [], 4, 5, "", None, 8])
>>> list(truthy_objects)
[1, 4, 5, 8]
With a string method and a list of strings:
>>> names = [
... "valid_name",
... "123invalid",
... "AnotherValidName",
... "invalid-name",
... ""
... ]
>>> list(filter(lambda name: name.isidentifier(), names))
['valid_name', 'AnotherValidName']
filter() Common Use Cases
The most common use cases for the filter() function include the following:
- Extracting specific elements from an iterable based on a condition
- Removing unwanted elements (e.g.,
None, empty strings) from an iterable - Processing data collections to retain only items of interest
filter() Real-World Example
Imagine that you want to extract all the prime numbers in a given interval. To do that, you can start by coding a predicate function that takes an integer as an argument and returns True if the number is prime, and False otherwise. Then, you can use filter() to process the data:
>>> import math
>>> def is_prime(n):
... if n <= 1:
... return False
... for i in range(2, int(math.sqrt(n)) + 1):
... if n % i == 0:
... return False
... return True
...
>>> list(filter(is_prime, range(1, 51)))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
In this example, filter() extracts all the prime numbers in the range between 1 and 50. The algorithm used in is_prime() comes from Wikipedia’s article about primality tests. You can check out that article if you need more efficient approaches.
Related Resources
Tutorial
Python's filter(): Extract Values From Iterables
In this step-by-step tutorial, you'll learn how Python's filter() works and how to use it effectively in your programs. You'll also learn how to use list comprehension and generator expressions to replace filter() and make your code more Pythonic.
For additional information on related topics, take a look at the following resources:
- Filtering Iterables With Python (Course)
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Python's reduce(): From Functional to Pythonic Style (Tutorial)
- Python List Comprehension: Tutorial With Examples (Tutorial)
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- Python's map() Function: Transforming Iterables (Course)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Python Booleans: Leveraging the Values of Truth (Course)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.