In Python, the yield is a keyword that is used in Python to return some value from the function without finishing the states of a local variable. It means it stores all the states of the variable inside a function and later starts executing of the function from the last yield statement.
Syntax:
def fun():
yield expression
print(fun)
Advantage of Yield:
- It is the best statement used in the generator function to store a local variable's states and resume its execution from the last yield statement.
- Since the old state is retained, the flow doesn’t start from the beginning and hence saves time.
Disadvantage of Yield Keyword:
- Time and memory optimization of the code complexity, and sometimes it is hard to understand the yield statement's working logic.
Example:
def func_1():
yield "Welcome to the Python"
result = func_1()
for x in result:
print(x)
Output: Welcome to the Python
Related Content
Tags