Iterators and generators

3.15.2

Process records one at a time and understand why an iterator can be exhausted.

On this page

Iterable and iterator

An iterable can produce an iterator. Call iter() to obtain one and next() to advance it. An exhausted iterator raises StopIteration unless you supply a default to next(). A list can create a new iterator whenever you need another pass.

values = iter([10, 20])
print(next(values), next(values), next(values, None))
Example output
10 20 None

Yield records when needed

A function containing yield returns a generator iterator. Each iteration resumes its body until the next yield. This lets you filter a large file without holding every row in memory, as long as the caller does not collect them all.

def valid_amounts(values):
    for value in values:
        if value is not None:
            yield value

print(sum(valid_amounts([3, None, 7])))
Example output
10

Official references