Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python iterator interview: lazy calls, exhaustion and partial failure

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

An iterator interview trace asks when work executes, which values are consumed and what remains after a failure.

Download Python source kit

Operation contract

The receipt generator records a label immediately before each yield. Constructing it does not run that body; next consumes the first value; list consumes the rest. The final read returns no values because the iterator is exhausted. This trace tests execution timing rather than memorizing the output of an arbitrary arithmetic puzzle.

Failure and ownership boundary

A generator may perform external writes before yielding and may fail after emitting a prefix. Laziness alone provides neither rollback nor bounded memory: a consumer can immediately materialize every yielded result. Read the ownership rule before moving a side effect into an iterator. Python CSV ingestion: cap bytes, rows and fields before publication deliberately returns only a completely validated batch.

Working program

python
def receipt_stream(trace):
    for receipt_id in (41, 42):
        trace.append("read:" + str(receipt_id))
        yield receipt_id

trace = []
stream = receipt_stream(trace)
print(trace)
print(next(stream))
print(trace)
print(list(stream))
print(list(stream))

Output

Output
[]
41
['read:41']
[42]
[]

Costs and limits

The generator itself retains bounded loop state here, but the trace grows with every produced value and list(stream) allocates all remaining output. Report consumer storage as well as iterator state.

Common Mistakes

  • Creating a generator does not execute its body immediately.
  • A consumed prefix is not undone if later iteration fails.

Connected lessons

Python generators: lazy iteration does not make retained output free, Python iterators: exhaustion and repeatable collection ownership, Python CSV ingestion: cap bytes, rows and fields before publication.

Follow the related contract

Python object lookup interview: descriptor precedence before instance state.

python
iterator-interview
Storage details