Search code examples
pythonyield-return

unexpected output using yield statement


I now read about the difference between return and yield statements and understand everything, when I applied some tests as the tutorial I follow said that there is 3 option I can use it to get out the result by yield one of them is the next method and as you know to use the next method you should create it manually by adding it more than one time, the test I did is:

first case:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(i)

the expected result here is:

0
1
4
9
16
25
36
49
64
81

and it works fine as expected

second case:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(next(sq))

so, instead of print the next(sq) multiple times I put it into a loop and used it one time so, it should printout same result as the first function but instead, it printout that result:

1
9
25
49
81

I ran debug but I couldn't understand what happens exactly


Solution

  • You are yielding in the for loop, then immediately yielding again with next()

    def test(n):
        yield n*n
    
    def getSquare(n):
        for i in range(n):
            for x in test(i):
                yield x
    
    sq = getSquare(10)
    for i in sq:
        print("Before next: ", i)
        print("After next:  ", next(sq))
    

    Output:

    Before next:  0
    After next:   1
    Before next:  4
    After next:   9
    Before next:  16
    After next:   25
    Before next:  36
    After next:   49
    Before next:  64
    After next:   81