The yield statement in python is similar to return statement, the only difference is that whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously. When resumed, the function continues execution immediately after the last yield run. Thus yield allows a function to produce a series of values over time, instead of computing them at once and sending them back all at once like a list. Yield produces a sequence of values and are used in generator function.
Example ofyield in python:-
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
# Driver code to check above generator function
for value in simpleGeneratorFun():
In above program output is 1,2,3 because when for loop run over simpleGeneratorFun(), simpleGeneratorFun() is called and within that function first yield is encountered therefore returning 1, again when loop runs, function resumes execution immediately after the last yield run therefore returning 2 and so on.