Comprehensions
We've already seen a lot of Python's for
loop. It allows us to loop over any object that supports the iterable protocol and do something specific with each of the elements in turn.
Supporting the iterable protocol simply means an object has an __iter__
method that returns another object that supports the iterator protocol. Supporting the iterator protocol is a fancy way of saying it has a __next__
method that either returns the next object in the sequence, or raises a StopIteration
exception when all objects have been returned.
As you can see, the for
statement, in spite of not looking terribly object-oriented, is actually a shortcut to some extremely object-oriented designs. Keep this in mind as we discuss comprehensions, as they, too, appear to be the polar opposite of an object-oriented tool. Yet, they use the same iteration protocol as for
loops. They're just another kind of shortcut.
List comprehensions
List comprehensions are one of the most powerful tools in Python, so...