iteration
filter()
Yields items from iterable for which function(item) is truthy. If function is None, filters out falsy items.
filter(function, iterable) Parameters
| Parameter | Purpose |
|---|---|
| function | Predicate returning truthy to keep; None keeps truthy items |
| iterable | Source iterable to filter |
Examples
list(filter(lambda x: x > 2, [1, 2, 3, 4])) Returns [3, 4]
list(filter(None, [0, 1, '', 'a', None])) Returns [1, 'a']
list(filter(str.isdigit, ['1', 'a', '2'])) Returns ['1', '2']
Gotcha
Returns an iterator (lazy) — not a list. List comprehensions are often more readable: [x for x in xs if pred(x)].
Related built-ins
map()
Applies a function to each item of one or more iterables, yielding results lazily. Returns a map object (iterator), not a list.
any()
Returns True if any element of the iterable is truthy. Short-circuits on the first truthy value.
all()
Returns True if every element of the iterable is truthy (or if the iterable is empty). Short-circuits on the first falsy value.
enumerate()
Yields (index, item) tuples from an iterable. Preferred over manual index counters in for-loops.
zip()
Pairs elements from multiple iterables into tuples, stopping at the shortest. With strict=True, raises ValueError if lengths differ.