Python Practice Question 6: Generator Exhaustion
Python · Test 1 · question 6 of 10
A developer builds a generator expression once and passes it to two aggregate functions: g = (x * x for x in range(3)); print(sum(g), sum(g)). What is printed?
Show answer and explanation
Answer:
A generator expression produces a generator object: a lazy, single-pass iterator. It computes 0, 1, 4 one value at a time as it is consumed, and it does not store them. The first sum(g) pulls all three values and returns 5, leaving the generator exhausted. The second sum(g) iterates over an iterator that immediately signals it has no more items, so it sums nothing and returns the start value 0.
Option A is what you would get with a list comprehension, [x * x for x in range(3)], because a list can be iterated any number of times. To reuse lazily generated values, build a list or create a new generator for each pass.
Option C has the order backwards; the arguments are evaluated left to right, and the first pass is the one that sees the data.
Option D is wrong because StopIteration is how an iterator tells a for loop or a consumer like sum() that it is finished. The consumer catches it and ends normally; an exhausted iterator just looks empty.
References: Glossary: iterator; Expressions: Generator expressions