Python Function Reference

filter

Select the items of an iterable for which a function returns a truthy value.

Python 3.13
filter(function, iterable)
function
A condition function that receives an item; with None, truthy items are selected.
Callable | None
iterable
The items to select from.
Iterable

Return value

An iterator of matching items; wrap it in list() to get a list.

Examples

Keeping numbers greater than two

Python 3.13
print(list(filter(lambda x: x > 2, [1, 2, 3, 4])))
[3, 4]

Keeping truthy values

Python 3.13
print(list(filter(None, [0, 1, '', 'a', None])))
[1, 'a']

Details

Items are checked only when the result is iterated over.

See also

Where to learn