Thus, the generator allows you to go through the elements of an object only once and its reuse is impossible - you need to create a new one. Generator functions In the previous section we looked at a generator of the form: (expression for item in iterable if condition). This expression is a special case of using a generator function. the same statement as a regular function — def. The difference is that yield is used, which returns a generator object, instead of the return statement, which immediately returns a value.
Let's look at how a generator function works using Fibonacci numbers as an example: def func(n): fb1 = 0 fb2 = 1 for i in range(1,n): yield fb2 fb_sum = fb1+fb2 fb1 = fb2 fb2 = fb_sum fb = func(7) print(fb) for i in fb: print(i) > <generator object func at 0x7f87e275e510> 1 1 2 3 5 8 As we can see, from the console, when calling the func(7) function, the fb australia email list generator is created. At each new iteration, the yield operator pauses the execution of the following instructions and returns the value of fb2. Further calls to the next(fb) method will cause the function to continue execution from the beginning until the next yield operator.
At the same time, as we can see, the values of the intermediate variables fb1 and fb_sum are fixed and changed in accordance with the code. The generator function supports the use of multiple yield operators. In this case, the value on the right side of the operator is returned, and the code on the subsequent next() is executed in the same way until the next yield. In this way, you can create coroutine functions with the ability to pause and resume program execution at the entry and exit points of yield.
A generator function is defined using
-
- Posts: 894
- Joined: Mon Dec 23, 2024 3:18 am