September 2021
Beginner to intermediate
352 pages
11h 27m
English
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.
yieldIf 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 ...