Yield Statement In Python
The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.
The yield statement hauls the function and returns back the value to the function caller and restart from where it is left off. The yield statement can be called multiple times. While the return statement ends the execution of the function and returns the value back to the caller. The function returns nothing without it. In Python generators, the yield function is used for replacing the return function that sends back the value to the user without ruining local variables.
- Yield returns the generator object.
- It can run multiple times.
- Code can be executed in the next function call after the yield statement.
- This statement can resume from where it is left off or paused.
- The yield statement hauls the function and returns back the value to the function caller.
What is Generator?
Python generators are used as a method for generating the iterators. Generators have automatically handled the task. A generator can be defined as the special function that returns an object of the generator to the caller.
In simple words, a generator is referred to the function that returns an iterator that we can iterate upon. In Python, it is very easy to create a generator and it uses the yield statement instead of the return statement.
Example 1:
# Python Code for using yield statement
def myfunction(a, b):
add = a + b
yield add
sub = a - b
yield sub
mul = a * b
yield mul
div = a % b
yield div
# generator runs with for loop for getting all values
for value in myfunction(49,45):
print(value)
Output:
94
4
2205
1.08
Example 2:
# Python code for using the yield statement
def printoutput(String) :
for i in String:
if i == "a":
yield i
# string initialization
String = "Tutorial and examples"
ans = 0
print ("The number of 'a' in the string is : ", end = "" )
String = String.strip()
for j in printoutput(String):
ans = ans + 1
print (ans)
Output:
The number of 'a' in the string is : 3
Explanation: In the above examples, we have seen the use of yield statement. The yield statement hauls the function and returns back the value to the function caller and restart from where it is left off.
Conclusion
In the above article, we have discussed the yield statement in Python. Also, we have understood the concepts of yield statement and know how to use it in our Python programs.