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, the need to iterate over sequences 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 the related concepts of Python’s iteration protocol, a method-call model used by the for loop, and fills in some details on list comprehensions, which are a close cousin to the for loop that applies an expression to items in an iterable.

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 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 also provides a shorter final installment in this story, where we’ll learn about user-defined iterable objects coded with classes.

In this chapter, we’ll also sample additional iteration tools in Python, and touch on the new iterables available in Python 3.X—where the notion of iterables grows even more pervasive.

One note up front: some of the concepts presented in these chapters may seem advanced at first glance. With practice, ...

Get Learning Python, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.