JuniorCodeCommonNot answered yet
What does listing a generator twice print?
Predict both lines.
g = (x for x in range(3))
print(list(g)) # (1)
print(list(g)) # (2)
Determine the output and explain.
(1) [0, 1, 2], (2) []. Generators are lazy and single-pass — once exhausted, they yield nothing on a second iteration. Re-create the generator, or materialize it into a list, if you need to iterate more than once.
- ✗Expecting a generator to restart on a second iteration
- ✗Thinking exhaustion raises StopIteration to the caller of list()
- ✗Reusing a generator where a list is needed
- →Why does
list()return[]rather than raising on an exhausted generator? - →When is a one-pass generator preferable to materializing a list?