Once I use a generator once, it can't be used again. Why is this?
Consider the following code:
def generator(n):
a = 1
for _ in range(n):
yield a
a += 1
def run_generator(generator):
for a in generator:
print(a, end = " ")
If I were to execute this:
count_generator = generator(10)
run_generator(count_generator)
run_generator(count_generator)
It would only print:
1 2 3 4 5 6 7 8 9 10
Basically, the generator just dies after a single execution.
I know that the fact that a generator can only be used once is something built into Python, but why is it like this? Is there a specific reason to only allowing a generator object to be executed once?