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.

>>> def squares(value = 5):
... while True:
... value = value + 1
... yield (value - 1) * (value - 1)
>>> generator = squares()
>>> next(generator)
>>> next(generator)
>>> next(generator)

It starts generating the squares from number five!

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 and I placed in it the code shown below:

def counter_up_down(value = 1):
yield from range(1, value, 5)
yield from range(value, 0, -3)

I run the file into terminal and this is the output:

ddn_ro@ddn:/mnt/c/Users/dumit/Desktop$ python3
[1, 6, 11, 16, 21, 26, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3]

Leave a Reply