Search code examples
pythonyield-from

Using yield won't generate new numbers (Using next function)


I am trying to use yield to generate new numbers on each iteration as shown below:

def nextSquare():
    i = 1
  
    # An Infinite loop to generate squares 
    while True:
        yield i*i                
        i += 1  # Next execution resumes 
                # from this point

When I try:

>>> for num in nextSquare():
    if num > 100:
         break    
    print(num)

I get the desired output:

1
4
9
16
25
36
49
64
81
100

but when I try: next(nextSquare())

it always yields the same old result. Am I doing something wrong? Instead of generating new numbers in a for loop I am interested in generating on demand.


Solution

  • As suggested in the comments, calling nextSquare everytime generates a fresh iterator and so I changed my code to:

    gen = nextSquare()
    

    and onDemand calling of next(gen) yields expected result.