This is my piece of code with two generators defined:
one_line_gen = (x for x in range(3))
def three_line_gen():
yield 0
yield 1
yield 2
When I execute:
for x in one_line_gen:
print x
for x in one_line_gen:
print x
The result is as expected:
0
1
2
However, if I execute:
for x in three_line_gen():
print x
for x in three_line_gen():
print x
The result is:
0
1
2
0
1
2
Why? I thought any generator can be used only once.
three_line_gen
is not a generator, it's a function. What it returns when you call it is a generator, a brand new one each time you call it. Each time you put parenthesis like this:
three_line_gen()
It is a brand new generator to be iterated on. If however you were to first do
mygen = three_line_gen()
and iterate over mygen
twice, the second time will fail as you expect.
no, you can not iterate over a generator twice. a generator is exhausted once you have iterated over it. you may make a copy of a generator with tee
though:
from itertools import tee
one_line_gen = (x for x in range(3))
gen1, gen2 = tee(one_line_gen)
# or:
# gen1, gen2 = tee(x for x in range(3))
for item in gen1:
print(item)
for item in gen2:
print(item)
for the other issues see Ofer Sadan's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With