pythongeneratoryield-keyword

Can generator be used more than once?


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.


Solution

  • 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.