|
Exit:
First result is 1 Second result is 2 Third result is 3
Difference between generator function and normal function —
- When the function exits, the function is suspended and control is transferred to the caller.
- When the function exits, StopIteration is automatically called on subsequent calls.
- Local variables and their states are remembered between successive calls. >
- A generator function contains one or more yield statements instead of a return statement.
- Since methods such as
_next_ ()
and_iter_ ()
are implemented automatically, we can iterate over the elements usingnext ()
.
There are various other expressions that can simply be coded similar to lists, but instead of parentheses, we use parentheses ... These expressions are intended for situations where the generator is immediately used by the enable function. A generator expression allows you to create a generator without the yield keyword. However, it does not share all the power of the generator created with the yield function. Example:
|
Output:
0 1 4 9 16 25 36 49 64 81
We can also generate cn Source using generator expressions:
|
You move:
[’k’,’ e’, ’e’,’ g’]
This article is provided by Chinma Lenka . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.