Iteration and Optimization
If the last section’s for loop looks like the list comprehension expression introduced
earlier, it should: both are really general iteration tools. In fact, both will work on any
object that follows the iteration protocol—a pervasive idea in Python that essentially
means a physically stored sequence in memory, or an object that generates one item at
a time in the context of an iteration operation. An object falls into the latter category
if it responds to the iter built-in with an object that advances in response to next. The
generator comprehension expression we saw earlier is such an object.
I’ll have more to say about the iteration protocol later in this book. For now, keep in
mind that every Python tool that scans an object from left to right uses the iteration
protocol. This is why the sorted call used in the prior section works on the dictionary
directly—we don’t have to call the keys method to get a sequence because dictionaries
are iterable objects, with a next that returns successive keys.