In Python, **yield** is a keyword that is commonly used in generator functions to generate serialized values without holding the entire sequence in memory.
When the function is called and contains yield statement, it does not immediately execute all the code in the function body. Instead, it will return a generator object each time the generator object's __next__() method, the function body will be changed from the last yield Execution continues where the statement left off until the next yield The statement or function ends.
As an example, the following code shows a simple generator function that uses yield Statement produces a sequence of numbers:
1 | def number_generator(n): |
Here, **number_generator()** Function usage yield Statement produces a sequence of numbers. When the function is called, it returns a generator object **my_generator**. Each time the generator object is called __next__() method, the function body will be changed from the last yield Execution continues where the statement stopped until the function ends or is encountered again yield statement. Since generators only produce values when needed, they can reduce memory usage.