python - Why does next() always display the same value? -


i practicing yield statement. have written following function in python 2.7:

>>> def mygen(): ...     = 0 ...     j = 3 ...     k in range(i, j): ...         yield k ... >>> mygen().next() 0 >>> mygen().next() 0 >>> mygen().next() 0 

whenever call mygen().next() displays output 0, instead of 0, 1, 2 & stopiteration. can please explain this?

you recreating generator each time, starts beginning each time.

create generator once:

gen = mygen() gen.next() gen.next() gen.next() 

generator functions produce new iterator every time call them; way can produce multiple independent copies. each independent iterator invocation of function can stepped through separately others:

>>> def mygen(): ...     = 0 ...     j = 3 ...     k in range(i, j): ...         yield k ... >>> gen1 = mygen() >>> gen2 = mygen() >>> gen1.next() 0 >>> gen1.next() 1 >>> gen2.next() 0 >>> gen2.next() 1 >>> gen1.next() 2 >>> gen1.next() traceback (most recent call last):   file "<stdin>", line 1, in <module> stopiteration 

note want use next() function instead of calling generator.next() directly:

next(gen) 

generator.next() considered hook (python 3 renamed generator.__next__() , next() function official api invoke in cross-version compatible way.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -