Skip to Content
Python Distilled
book

Python Distilled

by David M. Beazley
September 2021
Beginner to intermediate
352 pages
11h 27m
English
Addison-Wesley Professional
Content preview from Python Distilled

6. Generators

Generator functions are one of Python’s most interesting and powerful features. Generators are often presented as a convenient way to define new kinds of iteration patterns. However, there is much more to them: Generators can also fundamentally change the whole execution model of functions. This chapter discusses generators, generator delegation, generator-based coroutines, and common applications of generators.

6.1 Generators and yield

If a function uses the yield keyword, it defines an object known as a generator. The primary use of a generator is to produce values for use in iteration. Here’s an example:

def countdown(n):
     print('Counting down from', n)
     while n > 0:
          yield n
          n -= 1

# Example use ...
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 Testing with pytest

Python Testing with pytest

Brian Okken
Robust Python

Robust Python

Patrick Viafore

Publisher Resources

ISBN: 9780134173399