On this page
filter
Prev: exit | Up: __builtins__ | Next: float
Rel: all, any, enumerate, iter, aiter
Ref: docs.python.org — filter
Tags: #public #python3 #builtins
Import & Availability
# Built-in (available globally without import)
from builtins import filter
Overview & Signature
filter(function, iterable, /)
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
Usage
evens = list(filter(lambda x: x % 2 == 0, range(6)))
assert evens == [0, 2, 4]
# predicate=None filters out falsy values
assert list(filter(None, [0, "", "ok", None, 5])) == ["ok", 5]
Gotchas
- Returns a lazy single-use iterator: Often clearer as a generator/list comprehension (
[x for x in xs if x % 2 == 0]). filter(None, xs)drops0and""too: Use[x for x in xs if x is not None]if you only want to dropNone.
REPL Inspect
help(filter)
Linked from
- tuts/python3/__builtins__
- tuts/python3/__builtins__/__builtins__
- tuts/python3/__builtins__/aiter
- tuts/python3/__builtins__/all
- tuts/python3/__builtins__/anext
- tuts/python3/__builtins__/any
- tuts/python3/__builtins__/enumerate
- tuts/python3/__builtins__/exit
- tuts/python3/__builtins__/float
- tuts/python3/__builtins__/iter
- tuts/python3/__builtins__/len
- tuts/python3/__builtins__/map
- tuts/python3/__builtins__/next
- tuts/python3/__builtins__/reversed
- tuts/python3/__builtins__/sorted
- tuts/python3/__builtins__/zip
Related notes
- tuts/python3/__builtins__/__builtins__ Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/aiter Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/all Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/any Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/enumerate Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/exit Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/float Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/iter Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__ links to this page; shared tags: #builtins
- tuts/python3/__builtins__/anext links to this page; shared tags: #builtins