There is a lot of things in building  iterators in Python; we have to implement a class with iter() and next() method, keep track of internal variable states, raise StopIteration when there were no values to be returned, etc.

Python Generators

Python generators are used to create the iterators, but with a different approach. Generators are simple functions that return an iterable set of items, one at a time, in a unique way.

If the function contains at least one yield statement (it may include other yield or return statements, then it becomes a Generator function.

The main difference between normal function and Python Generators is that the return statement terminates the function entirely; the yieldstatement pauses the function saving all its states and variable values and later continues from there on successive calls.

#python #python generators

Python Generators: How to Create Iterators using Yield
1.25 GEEK