3.5 Using generator expressions
We’ve shown some examples of generator expressions already in the Lazy and eager evaluation section of Chapter 2, Introducing Essential Functional Concepts. We’ll show some more later in this chapter. In this section, we’ll introduce some more generator techniques.
Python collections are described as iterable. We can use a for
statement to iterate over the values. The key mechanism is the ability of a collection to create an iterator object to be used by the for
statement. This concept generalizes to encompass a function that is an iterator over values. We call these generator functions. We can also write generator expressions.
It’s common to see generator expressions used to create the list
or dict
literals through list comprehension or a dictionary comprehension syntax. This is a list comprehension example, [
x
**2
for
x
in
range
(10)
]
, a kind of list display. A list comprehension is one of several places in Python where...