Can generator be used more than once?

后端 未结 3 993
遇见更好的自我
遇见更好的自我 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

    Yes, generator can be used only once. but you have two generator object.

    # Python 3
    
    
    def three_line_gen():
        yield 0
        yield 1
        yield 2
    
    iterator = three_line_gen()
    print(iterator)
    for x in iterator:
        print(id(iterator), x)
    
    iterator2 = three_line_gen()
    print(iterator2)
    for x in iterator2:
        print(id(iterator2), x)
    

    And the result is:

    
    4328784304 0
    4328784304 1
    4328784304 2
    
    4328784376 0
    4328784376 1
    4328784376 2
    

提交回复
热议问题