Skip to Content
Advanced Python 3 Programming Techniques
book

Advanced Python 3 Programming Techniques

by Mark Summerfield
February 2009
Intermediate to advanced
68 pages
1h 51m
English
Addison-Wesley Professional
Content preview from Advanced Python 3 Programming Techniques

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python Network Programming Techniques

Python Network Programming Techniques

Marcel Neidinger
Scientific Computing with Python 3

Scientific Computing with Python 3

Claus Führer, Claus Fuhrer, Jan Erik Solem, Olivier Verdier

Publisher Resources

ISBN: 9780321637727