Python Reference ยท Built-in Functions
Python filter() function
Reference for Python filter(): keep the items of an iterable for which a function returns true, the lazy iterator result, None as the function and comprehension alternatives.
filter() takes a function and an iterable and returns an iterator over the items for which the function returns a true value. Items that fail the test are skipped. Nothing is computed until you iterate over the result.
If you pass None instead of a function, filter() keeps the items that are themselves truthy. In everyday code a list comprehension with an if clause often reads better, but filter() shines when you already have a named predicate function or want to stay lazy.
evens = filter(lambda n: n % 2 == 0, range(10)) print(list(evens)) # [0, 2, 4, 6, 8]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
filter(function, iterable)
| Name | Description |
|---|---|
function |
Called with one item at a time; the item is kept if the result is true. Use None to keep truthy items. |
iterable |
The source of items: a list, string, generator, file and so on. |
Return value: a filter iterator yielding the kept items in their original order.
Raises: TypeError if iterable is not iterable or the function cannot be called with one argument. Exceptions raised by the function appear while you iterate.
Usage notes
- It is an iterator, not a list. Python 2 returned a list; Python 3 does not. Use
list(filter(...))when you need one, and remember that an iterator can be consumed only once. - Truthiness decides. The function does not have to return
True; any truthy value keeps the item, including non-empty strings and non-zero numbers. filter(None, xs)drops0,0.0,"",None,Falseand empty containers. Be careful when zero is a valid value.- One iterable only. Unlike
map(),filter()takes a single iterable. - Comprehensions vs
filter().[x for x in xs if cond(x)]is usually clearer for inline conditions. Preferfilter()when passing an existing function or composing lazy pipelines. - The opposite is
itertools.filterfalse(), which keeps items where the function is false. - Original data is untouched.
filter()never mutates its input. - Side effects run late. Because it is lazy, a predicate that prints or logs runs only when the result is consumed.
Related
map(),sum(),any(),all(),sorted()- Lessons: Higher-order functions, List comprehensions