Comprehensions

Lesson 12 of 20

Replace clunky loops with one readable line — build lists and dicts with comprehensions and watch them assemble.

The big picture

A whole loop in one line

Comprehensions build brand-new collections in a single expression: transform every element, filter some out, done.

Loop Power, One Line

A comprehension builds a whole list in a single expression — transform, filter, finished.

Fixed Word Order

Every comprehension reads the same way: expression, then for, then an optional if.

Dicts Too

Swap the brackets for braces and you build dictionaries instead of lists.

Fresh Results

Comprehensions never mutate the source — you always get a brand-new collection.