Shivam Sahil
Shivam Sahil

Reputation: 4925

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.

Upvotes: 0

Views: 85

Answers (1)

Shivam Sahil
Shivam Sahil

Reputation: 4925

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.

Upvotes: 2

Related Questions