elinx elinx - 3 months ago 11
Python Question

Infinite sequencing number generator not work in python?

I am trying to implement a nature number generator which can generator infinite numbers, my code:

def nature():
s = 0
while True:
yield s
s += 1


when I use
next(nature())
, I get a sequence of 0s, why this? and how to fix it?

>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0

Answer

Every time you call nature() you create a new generator. Instead do this:

n = nature()
next(n)
next(n)
next(n)