Using the for statement with iterable collections
Python allows us to use the for
statement with any kind of collection. We can write a statement like for x in coll
to process list
, set
, or the keys of a dict
. This works because all of the Python collections have common abstract base classes, defined in the collections.abc
module.
This works via a common feature of the base classes, Sequence
, Set
, and Mapping
. The Iterable
mix in the class is part of each class definition. The implementation of this abstraction is our guarantee that all of the built-in collections will cooperate with the for
statement.
Let's open up the internals to see how it works. We'll use this compound for
statement as a concrete example:
for x in coll: print(x)
Conceptually, this compound statement starts with something very much like this assignment: coll_i=iter(coll)
. This will get an iterator object for the coll
collection. This iter()
function will leverage the special method __iter__()
to produce the...