Tutorial on Python Generators
Generators are a subset of iterators. A generator function is a function that has a yield statement instead of a return statement. It returns a generator object which you can iterate through. range() is an example of a generator function.
Here we create a “generator function” called count_by_two. You pass in the limit to which you want to count (in our case 5) …
When you invoke the count_by_2 generator function, you get a “generator” which we store in variable “count2_generator”. Calling “next” on this generator (like we do line 11) will give us the result of the yield statement on line 4. The count_by_two function pauses every time it reach the yield statement. It continues when the next “next” is called.
If the count_by_2 function reaches the end of the function without hitting a yield, a “StopIteration” exception is raised. Or the function could also have raised the StopIteration explicitly. So when we call “next” in line 11, we put it in a try block to catch this StopIteration and know when to break out of the while loop.