Skip to Content
Learning Python, 6th Edition
book

Learning Python, 6th Edition

by Mark Lutz
February 2025
Intermediate to advanced
1172 pages
42h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Python, 6th Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098171292Errata PageSupplemental Content