Search code examples
pythonpython-3.xgenerator

Why generator function does not work with the next call?


A generator function:

def getPositiveCount():
    n = 0
    while n<100:
        yield n
        n+=1

The generator function above does not do the expected when called in a next(..) method. Why does the next call return 0 all the times?

print(next(getPositiveCount())) # prints 0
print(next(getPositiveCount())) # prints 0; should've printed 1
print(next(getPositiveCount())) # prints 0; should've printed 2

However, it works just fine if I set it up in a loop:

for i in getPositiveCount():
    print(i)

# prints 0,1,2 ... 99
    

This as well, again, makes me ask, are generator functions the same as generator expressions (that normally uses a range, xrange or similar kind of builtins)? e.g. the next call in a generator expression works perfectly:

squares = (n** 2 for n in range(5))
print(next(squares)) # 0
print(next(squares)) # 1
print(next(squares)) # 4

Solution

  • Each call to getPositiveCount() creates a brand new generator. You are thinking of this:

    gen = getPositiveCount()
    print(next(gen))
    print(next(gen))
    print(next(gen))