Consequences and next steps
There are three important consequences to the way a for
statement uses coll_i= iter(x)
and x=next(coll_i)
:
We can write generator expressions which implicitly have the required interface to work as an
Iterable
classPython gives us a way to write generator functions which will work as an
Iterable
classWe can create our own classes which implement the special method names required to implement the
Iterable
abstract base class
We'll start by writing generator expressions. We can use these to create list
, set
, and mapping "comprehensions." A comprehension is an expression that defines the contents of a collection.
We'll look at writing generator functions. The yield
statement changes the semantics of a function from being "simple" (or "ordinary") to being a generator.
While class definitions are the subject of Chapter 11, Class Definitions, we won't dig deeply into how we can create our own unique collections. Python already offers so many collections that defining our...