What happens when you iterate over a generator twice?
Question
A generator reads lines and yields the positive numbers. One part of the code takes the first value for a preview. Another part then sums the stream. The team expected a total of 19.
Predict the exact output, line by line, and explain it. Then change the code so it prints the first value, the number of values and the full total. It must read the input only once.
def durations(lines): for line in lines: print("read", line) value = int(line) if value > 0: yield value stream = durations(["0", "12", "-3", "7"]) print("created") first = next(stream) print("first:", first) print("total:", sum(stream)) print("again:", list(stream))
Show hints (3)
- "WHEN IT STARTS"
Calling
durations(...)does not run its body yet. The body runs only when someone asks for a value. So where does the firstreadline appear? - "WHERE IT RESUMES"
next(stream)runs until the firstyieldand pauses there.sum(stream)continues from that pause. Can it still see 12? - "ONE PASS"
A generator can be read only once. Track the first value, the count and the total in one loop. Or, if the data is small, keep the values in a list.
Show checked explanation
A generator is a one-time stream. Its body starts on the first next(), pauses at each yield and resumes from there. So next() took 12, and sum() saw only 7. A finished generator stays empty: list() gets [] with no error. Read it once, or keep the values in a list.
def durations(lines): for line in lines: value = int(line) if value > 0: yield value first = None count = 0 total = 0 for value in durations(["0", "12", "-3", "7"]): if first is None: first = value count += 1 total += value print("first:", first, "count:", count, "total:", total)
first: 12 count: 2 total: 19
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
The starter prints eight lines. Here they are, grouped by the step that causes them:
| step | read lines | then prints |
|---|---|---|
durations(...) | none | created |
next(stream) | read 0, read 12 | first: 12 |
sum(stream) | read -3, read 7 | total: 7 |
list(stream) | none | again: [] |
Calling a function that contains yield does not run its body. It only returns a generator object. That is why created prints before any read line.
next(stream) runs the body until the first yield. It reads 0 and skips it. Then it reads 12, hands out 12 and pauses. The generator keeps its local variables and its place in the loop. One next() call can read several lines. It stops only when it reaches a yield.
sum(stream) resumes from that pause. 12 was already handed out, so sum never sees it. sum gets 7, the loop ends and the function returns. Now the generator is finished ("exhausted"), and it stays that way. list(stream), a second sum or a new for loop all get nothing. There is no error, which is why this bug is easy to miss.
The fix reads the stream once. It updates the first value, the count and the total in the same loop. The total is 12 + 7 = 19.
If the data is small, a list is simpler. A list can be read any number of times:
values = list(durations(["0", "12", "-3", "7"])) print(values, sum(values))
This prints [12, 7] 19. The cost is memory for every value.
Common mistakes
- Giving one generator to two consumers, such as a preview and a total. The second consumer starts where the first one stopped and silently misses values.
- Calling
next(stream)when the input may have no valid values. If the generator yields nothing,next()raisesStopIteration. Usenext(stream, None)and handleNone. - Expecting an error on a second pass. A used-up generator just yields nothing:
list(stream)is[]andsum(stream)is0. - Expecting
durations(lines)to reject bad input when you call it. A line such as"x"raisesValueErroronly when the loop reaches it, which may be much later.
Follow-up questions
- "Can't you just create a new generator for the second pass?" Yes, if the input can be read twice, like a list. Each call to
durations(lines)starts a fresh generator from the beginning. It repeats all the work. Iflinesis itself a generator or an open file, the new generator finds it used up and yields nothing. If a file changes between passes, the two passes see different data. - "Does a generator always save memory?" Only if nothing collects the values.
list(gen)builds the full list anyway, and here the input list is already in memory. A generator isn't faster by itself either. It does the same work, just later. It saves work only when the caller stops early, asnext()orany()do.
What a strong answer covers
Traces the output line by line. Explains that the body starts on the first next() and resumes after each yield. Knows that a finished generator stays empty with no error. Picks a fix that fits: one pass, a list, or a fresh generator if the input can be read again.
Open in interactive practice deck →