Middle
Is it possible to iterate over a generator twice? Why?
sobes.tech AI
Answer from AI
A generator in Python is an iterator that generates values "on the fly" and maintains its state between calls. It can only be traversed once because after a complete iteration, the generator is considered exhausted and cannot be restarted.
If you try to iterate over the generator a second time, it will immediately finish without yielding any elements.
Example:
def gen():
yield 1
yield 2
yield 3
g = gen()
print(list(g)) # [1, 2, 3]
print(list(g)) # [] — generator is already exhausted
To iterate over the data multiple times, you need to either create a new generator or use a collection that stores all elements (for example, a list).