filter() Filter by function
Last updated: 2026-09-22
filter() Filter by function
filter(function, iterable) keeps elements where function returns True; returns an iterator.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
filter(function, iterable)
⚙️ Parameters
| function Required | The predicate; pass None to use element truthiness directly. |
|---|---|
| iterable Required | The iterable to filter. |
Returns:A filter iterator; wrap with list() to materialize it.
💥 Raises
TypeError— Raised when function is not callable or iterable is not iterable.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
[2, 4]
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat does filter() return?
AIt returns a filter iterator (lazy); you must list(filter(...)) or iterate it to get the results.
QWhat does filter(None, lst) mean?
AWhen function is None, it filters by truthiness — equivalent to [x for x in lst if x], removing falsy values like 0, '', and None in one pass.
QWhich is better, filter() or a list comprehension?
AWhen semantically equivalent, the comprehension [x for x in lst if cond] is more readable; filter shines when paired with an existing function (e.g. filter(str.isdigit, s)).
QDoes filter call the predicate immediately?
ANo. filter is lazy: it calls the function element by element as iteration begins, which suits chained operations over large data.