Web Developer

How to iterate over data that has no iterator in Python

Data structures in Python are almost entirely already iterable. However, sometimes you do need a generator for the cases when the data is not iterable.

A generator is just a function that yields back to the section where it was called from. This is a signal for Python that you want to create a generator therefore it will automatically save the state of the function at the point of the yield statement. At this point you can return to it when next() is called.

A classic example will be a generator that generates the sequence of squares.

If you use Python 3.3 (or above) then you can take advantage of the yield from statement. It is a way of creating generator functions that use other iterators to generate the required values. I created the file.py and I placed in it the code shown below: