Chapter 3. Generator Expressions and Functions

A generator function or generator method is one which contains a yield expression. When a generator function is called it returns an iterator. Values are extracted from the iterator one at a time by calling its __next__() method. At each call to __next__() the generator function’s yield expression’s value (None if none is specified) is returned. If the generator function finishes or executes a return a StopIteration exception is raised.

In practice we rarely call __next__() or catch a StopIteration. Instead, we just use a generator like any other iterable. Here are two almost equivalent functions. The one on the left returns a list and the one on the right returns a generator.

We can iterate ...

Get Advanced Python 3 Programming Techniques 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.