Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

filter()

Lazily retains input items that pass the supplied predicate.

Version: Python 3.14; repository image, production runtime not attested

Syntax

filter(function, iterable, /)

Lazily retains input items that pass the supplied predicate.

Passing None applies ordinary truth testing. A filter iterator is exhausted after its values have been consumed.

The iterator yields original items whose predicate result has true truth value. Passing None tests each item directly. The zero and empty string disappear, leaving 2 and 4. The first list conversion consumes the filter; converting it again yields an empty list.

it = filter(None, [0, 2, "", 4])
assert next(it) == 2 and list(it) == [4] and list(it) == []

Examples

items = filter(None, [0, 2, "", 4])
print(list(items))
print(list(items))

Result

[2, 4]
[]

The iterator yields original items whose predicate result has true truth value. Passing None tests each item directly. The zero and empty string disappear, leaving 2 and 4. The first list conversion consumes the filter; converting it again yields an empty list.

Sources