

To restart the process, we’d need to create another generator object This also means that the iterator can only be iterated through once.

The generator function contains one or more yield statements.It maintains the states of the function so that later it can resume from that point, should it be called once again.Ī generator function features some basic differences from a regular function: yield acts like a pause button on a music player.return terminates the function’s execution.The difference arises from the effect these two each have on the function’s execution flow: In terms of values returned, both yield and return act the same. But it does have the twist of using yield statements, as opposed to regular functions, which usually use the return statement. Now, a generator being nothing more than a function, it’s fairly easy to create one. And I guess the simplest way I could describe the generators is this: a function that returns a generator object, which we can then use in our iteration process. Now let’s point out that all of that functionality is achievable with even less effort from our side, via these generators.
SAVE THE WORLD CODE GENERATOR PLUS
We saw how we needed to create and use a class that implemented both _iter_() and _next_() methods, plus we had to keep a close eye on the situation where we run out of elements and to raise a StopIteration exception as a direct consequence. We’ve seen how building an iterator in Python isn’t exactly the most straightforward thing to do. As a natural next step, as we’ll come to see in just a few moments, following the last article where we discovered and went over the topic of iterators, today we’ll take on another very important topic related to Python: generators.
