Yield usage in Python



The function of yield in the function is similar to return. The difference is that the function does not exit after yield returns the result each time, but returns the result

Each time the yield keyword is encountered, the corresponding result is returned, and the current running state of the function is retained, waiting for the next call. If

A function needs to execute an action repeatedly, and the result of each execution is needed. This scenario is very suitable for using yield.

The function containing yield becomes a generator, which is also an iterator. It supports getting the next value through the next method.

Basic use of yield:

def func():
    for i in range(0,3):
        yield i

f = func()
f.next()
f.next()


For the generator, when the function next is called, the value of the expression after yield of the generator will be obtained;

When the yield statement ends after the last loop, the generator will throw stopiteration exception;

In addition to the next function, the generator also supports the send function. This function can pass parameters to the generator.

def func(n):
    for i in range(0,n):
        val = yield i        
        print val

f = func(10)
f.next()
#f.send(None)
f.send(2)
f.send(10)
print f.next()

Read More: