Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Iterators and generators

An iterable can supply an iterator, whose next operation advances state and signals exhaustion with StopIteration.

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

Syntax

iterator = iter(source)

An iterable can supply an iterator, whose next operation advances state and signals exhaustion with StopIteration.

A generator function returns such an iterator and suspends its local execution at yield. Iterating an iterator returns that same object, so two references share progress and a completed iterator remains exhausted.

A list can instead supply a fresh independent iterator.

Examples

def squares(values):
    for value in values:
        yield value * value
g = squares([2, 3])
other = iter(g)
print(g is other, next(g), next(other))
print(next(g, "end"), list(g))
values = [2, 3]
a, b = iter(values), iter(values)
print(next(a), next(b))

Result

True 4 9
end []
2 2

A list can instead supply a fresh independent iterator.

Sources