Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

iter()

Constructs an iterator, optionally calling an object without arguments until it returns a matching sentinel.

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

Syntax

iter(object, /)
iter(callable, sentinel, /)

Constructs an iterator, optionally calling an object without arguments until it returns a matching sentinel.

The sentinel is consumed by the test and never yielded to the caller.

With one argument, iter obtains an iterator from the iterable or indexed sequence protocol. The two-argument form calls its callable without arguments. In CPython 3.14, the same sentinel object or an equal result ends iteration. Here the zero returned after 2 and 4 equals the sentinel, so it is consumed but never yielded. The underlying iterator still contains 8.

x = float("nan")
stream = iter([1, x, 2])
assert list(iter(stream.__next__, x)) == [1] and next(stream) == 2
values = iter([2, 4, 0, 8])
assert list(iter(values.__next__, 0)) == [2, 4] and next(values) == 8

Examples

values = iter([2, 4, 0, 8])
print(list(iter(values.__next__, 0)))
print(next(values))

Result

[2, 4]
8

With one argument, iter obtains an iterator from the iterable or indexed sequence protocol. The two-argument form calls its callable without arguments. In CPython 3.14, the same sentinel object or an equal result ends iteration. Here the zero returned after 2 and 4 equals the sentinel, so it is consumed but never yielded. The underlying iterator still contains 8.

Sources