The primary advantage of generators is their simplicity. Much less
boilerplate code has to be written compared to implementing an
Iterator class, and the code is generally much more
readable. For example, the following function and class are equivalent:

This flexibility does come at a cost, however: generators are forward-only
iterators, and cannot be rewound once iteration has started. This also
means that the same generator can't be iterated over multiple times: the
generator will need to be rebuilt by calling the generator function again.

User Contributed Notes 3 notes

This hardly seems a fair comparison between the two examples, size-for-size. As noted, generators are forward-only, meaning that it should be compared to an iterator with a dummy rewind function defined. Also, to be fair, since the iterator throws an exception, shouldn't the generator example also throw the same exception? The code comparison would become more like this:

I think to be more similar the samples in the function, throw a new exception is better. But looking into "Generator syntax" session, you can see there this: "An empty return statement is valid syntax within a generator and it will terminate the generator.". By this point of view, we can imagine that this is just to exemplify an usage of the empty return.