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

ParameterDescription
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

Keep matching itemsTry it yourself
numbers = [5, 12, 7, 20, 3]
print(list(filter(lambda n: n > 6, numbers)))

Output

[12, 7, 20]
Remove falsy valuesTry it yourself
print(list(filter(None, ["a", "", None, "b", 0])))

Output

['a', 'b']
The list comprehension equivalentTry it yourself
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 in list() 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

VersionChange
Python 3.0Added