Can generator be used more than once?

后端 未结 3 997
遇见更好的自我
遇见更好的自我 2021-02-13 07:18

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
         


        
3条回答
  •  臣服心动
    2021-02-13 07:45

    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.

提交回复
热议问题