For more information on topics covered in this lesson, check out these resources:
Using return vs yield in Generator Functions
You can use
return statements in generator functions to indicate that there is no more work for the function to do. When this happens during program execution, the function raises a
StopIteration exception when it encounters a
The return value from the function will be used as the exception’s initializer argument and will be stored in its
.value attribute. Here’s a simple generator that will produce
2 as requested, and then return
3 when finished To use it, we assign the function call to a variable, which becomes our generator object.
Then we use the function
next() with our generator as an argument to retrieve the next item from that generator. After using all of the items the generator will produce, another call to
next() raises the
StopIteration exception—in this case, with the return value of
3. We can actually see this happen.
The first two calls to
next() produce the values
2 from the
yield statements in the function. With a third call to
next(), we had used up all of the values the generator was prepared to provide, so a
StopIteration exception was raised. Finally, you were able to see the use of a
return statement in a generator function.
Become a Member to join the conversation.