Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Hash Doe Avatar asked Jul 30 '17 12:07

Hash Doe


2 Answers

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.

like image 133
Ofer Sadan Avatar answered Sep 27 '22 18:09

Ofer Sadan


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.

like image 28
hiro protagonist Avatar answered Sep 27 '22 18:09

hiro protagonist