Predicate-based selection
Keep records satisfying a validation or eligibility predicate before processing them.
Python · Function
filter() constructs an iterator containing elements from an iterable that pass a function's truth test. With None as the function, it removes false-valued elements.
filter() lazily iterates over an iterable and yields each element whose predicate produces a truthy result. Passing None uses each element's own truth value, so false elements are excluded; the result can be consumed like any other iterator.
filter(function, iterable, /)| Name | Type | Description |
|---|---|---|
function | callable or None | A callable tested against each element; use None to test elements by their own truth value. |
iterable | iterable | A sequence, iterable container, or iterator whose elements are examined. |
An iterator over elements of iterable for which function is true.
active_names = list(filter(lambda name: name.startswith("A"), ["Ada", "Grace", "Alan", "Linus"]))
print(active_names)Converts the lazy filter iterator to a list containing names that start with A.
Keep records satisfying a validation or eligibility predicate before processing them.
Remove empty strings, zeroes, None values, or other false-valued items from an iterable.
Process large or streaming inputs incrementally without immediately materializing a list.
filter() takes a function and an iterable, then constructs an iterator containing elements for which the function is true. The iterable can be a sequence, container, or iterator.
Follow-up: What happens when the function is None? Each element is tested directly, and false elements are removed.
The result is an iterator, so it is evaluated as it is consumed. Convert it with list() or another consumer when a materialized collection is needed.
Follow-up: How could the same behavior be expressed without filter()? Use a generator expression with the corresponding condition.
With function set to None, filter() applies the identity behavior: elements whose truth value is false are omitted. This is equivalent to iterating with an if item condition.
Follow-up: What is the complementary standard-library operation? itertools.filterfalse() selects elements for which the predicate is false.
itertools.filterfalse()map()generator expressionslist comprehensions