Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading