Trace a generator through one pass
Type one expression at a time and check its delimiters. · 179 words
A generator is a Python object that produces values on demand instead of storing an entire sequence in memory. This lazy behavior means work happens only when a value is requested, which helps when experiment predictions arrive as a long stream. A generator function uses yield to mark a value it can produce later. For example, define def scores(): print('made A'); yield 0.8; print('made B'); yield 0.9. Calling g = scores() creates the generator, but the function body has not started and nothing has printed.
The first next(g) resumes the function, prints made A, and returns 0.8. The second next(g) resumes after that yield, prints made B, and returns 0.9. After both values are consumed, the generator is exhausted: list(g) is [], and another next(g) raises StopIteration. A for loop started immediately after the first call would consume the second value. A loop started after exhaustion produces nothing. This one-pass rule is important in AI pipelines that stream model outputs, validation measurements, or file rows. The two print statements provide a hand-checkable trace of when each score is produced.
Check your recall
After g = scores() and one call to next(g), what has printed, what value was returned, and what will the next next(g) do?
Check your answer
It printed made A and returned 0.8. The next call resumes after the first yield, prints made B, and returns 0.9.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.