Chapter 14. Iterations and Comprehensions
In the prior chapter, we met Python’s two looping statements, while and for. Although they can handle most repetitive tasks programs need to perform, iterating over collections is so common and pervasive that Python provides additional tools to make it simpler and more efficient. This chapter begins our exploration of these tools. Specifically, it presents Python’s iteration protocol, a method-call model used by the for loop, and fills in some details on comprehensions, which are a close cousin to the for loop that apply an expression to each item in a collection.
Because these tools are related to both the for loop and functions, we’ll take a two-pass approach to covering them in this book—along with a postscript:
This chapter introduces their basics in the context of looping-based tools, serving as something of a continuation of the prior chapter.
Chapter 20 revisits them in the context of function-based tools, and extends the topic to include built-in and user-defined generators.
Chapter 30 provides a shorter final installment in this story, which will show us how to code user-defined iterable objects with classes.
One note up front: some of the concepts presented in these chapters may seem advanced at first glance. With practice, though, you’ll find that these tools are useful and natural. Although never strictly required, they’ve also become commonplace in Python code, so a basic understanding can help if you must read programs ...