Using a generator

The previous code can be simplified significantly by simply using a generator. Generator objects are iterators. This way, instead of creating a class, we can define a function that yield the values as needed:

def sequence(start=0):    while True:        yield start        start += 1

Remember that from our first definition, the yield keyword in the body of the function makes it a generator. Because it is a generator, it's perfectly fine to create an infinite loop like this, because, when this generator function is called, it will run all the code until the next yield statement is reached. It will produce its value and suspend there:

>>> seq = sequence(10)>>> next(seq)10>>> next(seq)11>>> list(zip(sequence(), "abcdef"))[(0, 'a'), (1, 'b'), ...

Get Clean Code in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.