Lesson 1.2

Control flow and comprehensions

A very common loop creates an empty list, iterates, transforms, and appends.

10mBeginner29.7k students

Overview

The shape most Python loops want to be

A very common loop creates an empty list, iterates, transforms, and appends. A comprehension expresses the same thing in one line that reads as a description of the result rather than a recipe for building it.

Comprehensions come in dict and set forms too, and a filtering clause folds the if into the same expression.

They stop helping when nested more than one level deep or when the expression grows a conditional inside a conditional. At that point an explicit loop is the readable choice, and readability is the entire point.

In this lesson you will:

  • Loop and branch idiomatically
  • Replace a build-up loop with a comprehension
  • Know when a comprehension hurts readability

Resources

Previous Lesson
Next Lesson
Control flow and comprehensions — Python Foundations for Data Work — Vertex