Chapters
Python114 chapters

ReferenceBuilt-in functions

filter()

Keeps the items for which the function is true.

Signature

filter(function, iterable)

Parameters

NameMeans
functioncalled on each item; None keeps the truthy ones
iterablewhat to walk

Returns

An iterator, so wrap it in list() to see it.

Example

Python
print(list(filter(lambda n: n % 2 == 0, [1, 2, 3, 4])))
print(list(filter(None, [0, 1, "", "a"])))

Output

[2, 4]
[1, 'a']

See also