Yield Keyword in Python
Like another function program, when we want to return some value from a function, we use a return statement. In Python, when we return a value in a function, we use the yield keyword. It returns the values one by one without destroying the states of the local variable.
The yield is a keyword 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.
In Python, if any function containing at least one yield statement, it termed as a generator. A generator function contains a yield statement inside their body to generate the series of values one by one in a loop.
The only difference between return and yield keyword is that the return keyword returns or prints the actual value of the function and exits from the function whereas, the yield keyword returns the values and continues executing the series one by one. It also does not exit from the function.
When the program is compiled, the Python yield statement/expression converts into the generator object. It holds the states of the yield statement or local variable to resume the execution from the same point later.
Let's write a program to use the yield statement inside a generator function and print the yield expression.
<generator object yield_fun at 0x00000248549CBBA0> <class 'generator'> 5 10 15 20
As we can see in the above output, we have used multiple yield statements inside the function to print the yield statement. All states of yield statements or local variables are stored in a function as a generator object to execute a series of yield statements. When the For loop iterates the function again, it starts execution of the yield statement at the same point where it was left. The process continues until the last yield statement is encountered.
Let's write a program to print the sequence of string in Python using the yield statement. simple.py
Welcome to the Python Tutorials @ the JavaTpoint.com
Write a program to generate a square of numbers from 1 to 100 using the yield statement.
In the above program, for loop continuously calls the function to execute a set of consecutive series until it reaches the yield statement.
Advantages of Yield keyword
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.