Chapter 8. More Advanced Functions
In Chapter 7, Basic Function Definitions, we looked at the core features of defining a function which returns a single result. Even functions with an implicit return
statement at the end of the suite of statements, or a function with a return
statement that has no expression, return a result: the None
object is the default return value. In this chapter, we'll look at functions which generate multiple results. A generator function defines an iterable: it can be used with a for
statement. This means that the generator doesn't produce a single object with all of the items in the result; instead it produces each item of the result separately.
Python offers generator expressions and comprehensions which complement the idea of generator functions. We can write simple expressions that represent a sequence of values which is generated one item at a time. We can use generator expressions to create list
, set
, or dict
objects via a comprehension...