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) 25 >>> next(generator) 36 >>> next(generator) 49