Iterators and generators
A list stores values that a caller can traverse again. An iterator records a position in a traversal, and each request advances that position. Confusing the two can turn a second calculation into an empty result without an exception.
Read control flow and
functions first. These examples use
invented read counts and the Python 3.13 standard library. Save the blocks in
page order as iterators_generators.py and run uv run python iterators_generators.py.
Separate a container from its iterator
Section titled “Separate a container from its iterator”iter(values) asks an iterable for an iterator. next(iterator) requests its
next value. A list supplies a new iterator for each call to iter, so two list
iterators can occupy different positions in the same list.
counts = [4, 0, 9]first_pass = iter(counts)second_pass = iter(counts)print("First iterator takes:", next(first_pass))print("First iterator still has:", list(first_pass))print("First iterator after exhaustion:", list(first_pass))print("Second iterator has:", list(second_pass))print("Original list:", counts)print("An iterator returns itself:", iter(first_pass) is first_pass)First iterator takes: 4First iterator still has: [0, 9]First iterator after exhaustion: []Second iterator has: [4, 0, 9]Original list: [4, 0, 9]An iterator returns itself: Truelist(first_pass) consumes every remaining value; it does not reset the
iterator. Asking iter for that iterator again also preserves its current
position. A loop stops when the iterator raises StopIteration.
single_value = iter([7])print("Only value:", next(single_value))try: next(single_value)except StopIteration as error: print("Exhausted iterator:", type(error).__name__)print("Explicit default:", next(single_value, "finished"))Only value: 7Exhausted iterator: StopIterationExplicit default: finishedThe optional second argument to next supplies a result when no value remains.
Choose a default that cannot be confused with a valid value, or handle
StopIteration explicitly.
A generator expression also has a position
Section titled “A generator expression also has a position”A generator expression delays its element calculations until a consumer asks
for values. sum, list, next, and a for loop all consume iterators.
The expression below retains no list of filtered counts.
selected_counts = (count for count in counts if count > 0)print("Selected total:", sum(selected_counts))print("Values after sum:", list(selected_counts))print("New expression:", list(count for count in counts if count > 0))Selected total: 13Values after sum: []New expression: [4, 9]map, filter, and zip also return iterators. The
paired-loop example uses
zip(strict=True) to reject unequal input lengths, but the resulting iterator
still advances as the loop consumes it.
Materialize an iterator with list when later calculations need repeated
access to the same values. For a single sum or count, a direct pass avoids
that additional collection. A generator does not remove storage already
occupied by its input list.
Suspend a function with yield
Section titled “Suspend a function with yield”A generator function contains yield. Calling it creates a generator without
executing its body. Each request resumes the body until the next yield,
and local variables keep their values between requests.
from collections.abc import Iterable, Iterator
def counts_at_least( values: Iterable[int], *, minimum: int = 1) -> Iterator[int]: """Yield nonnegative counts that meet a threshold in one pass.
Args: values: Nonnegative integer counts, which may come from an iterator. minimum: Nonnegative threshold for an emitted count.
Yields: Counts at least as large as minimum, in input order.
Raises: ValueError: During consumption, if minimum or a count is negative. """ if minimum < 0: raise ValueError("minimum must be nonnegative") for value in values: if value < 0: raise ValueError("counts must be nonnegative") if value >= minimum: yield value
source_iterator = iter([0, 5, 2, 8])filtered_iterator = counts_at_least(source_iterator, minimum=4)print("First yielded count:", next(filtered_iterator))print("Remaining selected counts:", list(filtered_iterator))print("Remaining source counts:", list(source_iterator))First yielded count: 5Remaining selected counts: [8]Remaining source counts: []The first request reads source values until one satisfies the condition. Later requests continue from that point. The source and filtered iterators therefore share progress; consuming one changes what remains available.
For n inputs, a complete traversal takes O(n) time and uses constant
additional state. Calling list on the result adds storage for the retained
values. These bounds assume constant-time comparisons between the counts.
Lazy execution also delays errors
Section titled “Lazy execution also delays errors”The validation in counts_at_least runs when the caller consumes the
generator. Merely constructing the generator does not validate its inputs.
An invalid record can also arrive after earlier records were already emitted.
invalid_threshold = counts_at_least([4], minimum=-1)print("Generator created before validation.")try: next(invalid_threshold)except ValueError as error: print("Threshold rejected during consumption:", str(error))
invalid_later = counts_at_least([4, -2, 8])print("Value before the invalid record:", next(invalid_later))try: next(invalid_later)except ValueError as error: print("Later count rejected:", str(error))Generator created before validation.Threshold rejected during consumption: minimum must be nonnegativeValue before the invalid record: 4Later count rejected: counts must be nonnegativeIf a program must validate a complete file before it writes any result, a partially consumed generator cannot establish that condition. Validate the whole input first, or use a separate design for temporary output and final publication. The file and CLI lesson uses complete validation before it creates an output file.
State the interface that a consumer needs
Section titled “State the interface that a consumer needs”Iterable[int] means that a caller can obtain an iterator of integers.
It does not promise indexing, a length, or a second successful traversal.
Iterator[int] also describes the stateful next interface. A generator fits
both interfaces.
The type annotation lesson explains why these annotations describe a contract without checking values at runtime. A consumer that needs only one pass should not require a list merely to obtain its values.
Practice with a stream
Section titled “Practice with a stream”Write a function that returns the number of records and their total in one
pass. Its input can be a list or an iterator, and an empty input is valid.
It must not build another list. Explain why calling sum before a second
loop fails for an iterator.
Show the solution and executable checks.
Both results can be updated while each value is available. A second pass is unnecessary. The count and total use constant additional state under a bounded integer cost model.
def summarize_stream(values: Iterable[int]) -> tuple[int, int]: """Count records and sum their values through one traversal.
Args: values: Integer values supplied by any iterable.
Returns: The record count and total, with two zeros for an empty input. """ record_count = 0 total = 0 for value in values: record_count += 1 total += value return record_count, total
practice_stream = iter([2, 7, 0, 3])print("Record count and total:", summarize_stream(practice_stream))print("Exhausted stream:", summarize_stream(practice_stream))assert summarize_stream([]) == (0, 0)assert summarize_stream([2, 7, 0, 3]) == (4, 12)assert summarize_stream(counts_at_least([2, 7, 0, 3])) == (3, 12)assert list(counts_at_least([0, 0], minimum=0)) == [0, 0]print("List, iterator, generator, empty, and zero-threshold checks pass.")Record count and total: (4, 12)Exhausted stream: (0, 0)List, iterator, generator, empty, and zero-threshold checks pass.Further reading
Section titled “Further reading”The Python 3.13 iterator tutorial
explains iter, next, and StopIteration. Its
generator section
explains how yield preserves local state between requests.
The collections.abc reference defines iterable and iterator interfaces. Use those interfaces to distinguish what a consumer requires from the concrete collection a caller supplies.