What is a generator in Python and what does yield do?

I recently encountered a lot of python code using yield code, which means that a function is a generator. What does it mean?
If a function uses yield to define a statement , then the function is not an ordinary function, but a generator, which means that the function is an iterable object .

Look at the following code:

def yield_test(n):  
    for i in range(n):  
        yield callMe(i)  #a
        print("i=",i)    #b  
    print("something else")  
    print("end.")  
  
def callMe(i):  
    return i*i 
    
for i in yield_test(3):
    print(i)

When the function yield_test is called for the first time , the code in the defined function does not execute the entire method in turn like other methods, but when the statement yield (place a) is executed , the subsequent function call result is returned.
Then when the for is executed for the second time, the function starts directly from position b . After encountering the yield statement, it returns to the for statement. The for statement is executed in turn .

The trial results are as follows:

0
i= 0
1
i= 1
4
i= 2
something else
end.

The generator can also be called directly as an iterable object: yield_test (3) .yield_test (3) ._ next_ () (python3.x used to be the next () function), and each call returns a value.

The benefits of using generators are:

  • The generator will turn the function into an iterable object, returning a value to the caller each time, reducing memory consumption (the same problem does not require a generator, you may need to use list to store data and return to the caller)
  • In the second iteration of the generator, the value of the variable before the yield statement will be saved, as if the function is stuck, and the second time will continue to execute the remaining code instead of restarting from the first line of the function.
Published 89 original articles · praised 83 · visits 3484

Guess you like

Origin blog.csdn.net/devin_xin/article/details/105639892