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]
filter()
Signature
filter(function, iterable)
Arguments
Argument | Description |
---|---|
function |
A function that returns a Boolean value and determines which elements to filter. |
iterable |
An iterable to be filtered, such as a list, tuple, set, generator, or iterator. |
Return Value
- A
filter
object that yields elements from the input iterable that satisfy the filtering condition checked byfunction
.
Note: If function
is None
, 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', 'True']
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:
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Python's reduce(): From Functional to Pythonic Style (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- Python Booleans: Use Truth Values in Your Code (Tutorial)
- Filtering Iterables With Python (Course)
- 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)