Yield Statement in Python
The yield statement is a special kind of function in Python. It’s useful when processing complex data structures. It is used in generators. This function keeps the same data without using global variables as in an ordinary function. It can interact with the for statement. We work only with sequences like strings, tuples, and lists.
The simple example of a generator with yield function:
>>> def city():
<generator object city at 0x00C7A5D0>
We have the generator with two items(“Warsaw” and “Moscow”). Now, we must create a iterator for this generator:
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
If you see a yield statement in a function, the function is a generator object. We use the next() function in the iterator to get an item from our generator.The yield function returns data. Each time next() is called in our iterator, the generator can resume where it finished. It really remember all values an the statement that was last executed.
def func_name(param1, param2,…)
The suite of statements must include at least one yield statement. The yield statement specifies the values emitted by the generator. Note that the expression is required.
When we see a return statement in a function, we should know that it ends our generator with StopIteration exception. The return statement have no return value with itself. We’ll see why:
Now, we can iterate:
>>> for x in bolo():
The return statement in our generator returns all values that where associated with the yield statement,