Chapter 13. Advanced Iteration: Looping Like Crazy

It’s often amazing how much time our programs spend in loops. This isn’t a surprise, as most programs exist to perform something quickly a whole heap of times. When it comes to optimizing loops, there are two approaches: (1) improve the loop syntax (to make it easier to specify a loop), and (2) improve how loops execute (to make them go faster). Early in the lifetime of Python 2 (that is, a long, long time ago), the language designers added a single language feature that implements both approaches, and it goes by a rather strange name: comprehension. But don’t let the strange name put you off: by the time you’ve worked through this chapter, you’ll be wondering how you managed to live without comprehensions for so long.
Bahamas Buzzers Have Places to Go
To learn what loop comprehensions can do for you, you’re going to take a look at some “real” data.
Operating out of Nassau on New Providence Island, Bahamas Buzzers provides island-hopping flights to some of the larger island airports. The airline has pioneered just-in-time flight scheduling: based on the previous day’s demand, the airline predicts (which is just a fancy term for “guesses”) how many flights they need the next day. At the end of each day, the BB Head Office generates the next day’s flight schedule, which ends up in a text-based CSV (comma-separated value) file.
Here’s what ...
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.
Read now
Unlock full access