O'Reilly logo

Advanced Python 3 Programming Techniques by Mark Summerfield

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required