Python 3 reference · Built-in Functions
Python filter() Function
Keep only the items of an iterable for which a function returns True. Returns a lazy iterator, not a list.
Python 3 Since 3.0
Syntax
filter(function, iterable)
Parameters
| Parameter | Description |
|---|---|
function |
Called with each item; keep the item if the result is truthy. None keeps truthy items. |
iterable |
The items to filter. |
Return value
An iterator over the kept items.
Examples
numbers = [5, 12, 7, 20, 3]
print(list(filter(lambda n: n > 6, numbers)))
Output
[12, 7, 20]
print(list(filter(None, ["a", "", None, "b", 0])))
Output
['a', 'b']
numbers = [5, 12, 7, 20, 3]
print([n for n in numbers if n > 6]) # usually clearer
Output
[12, 7, 20]
Good to know
filter()returns an iterator: wrap it inlist()to see the items, and remember it can only be used once.- A list comprehension
[x for x in items if cond]is often more readable, especially when you also transform the items.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
map()· Apply a function to every item of one or more iterables and return a lazy iterator of the results.sorted()· Return a new sorted list from any iterable. Supports a key function and reverse order; the original is left unchanged.any()· Return True if at least one item in an iterable is truthy. Returns False for an empty iterable and stops at the first truthy item.all()· Return True if every item in an iterable is truthy, or if the iterable is empty. Stops at the first falsy item.- Python List Methods and Comprehensions · tutorial
- Python Lambda · tutorial