Home / Python / Reference / Built-in functions

Python filter() function

Keep only the items for which a function returns True.

Syntax

filter(function, iterable)

Returns an iterator. A comprehension with if is often clearer. With None as the function it keeps the truthy items.

Parameters

functionreturns True to keep an item
iterablethe items

Return value

a filter iterator

Example

Code

nums = [3, 8, 11, 14, 20]
print(list(filter(lambda n: n % 2 == 0, nums)))
print([n for n in nums if n % 2 == 0])     # the same, as a comprehension
print(list(filter(None, ["a", "", "b", None])))

Output

[8, 14, 20]
[8, 14, 20]
['a', 'b']

Related

Learn it step by step in the free lesson Pythonic Python, with exercises that check your answers.