Caffeinated Coder
Book an appointment
Lesson 09 · Collections and functions

Comprehensions

A list comprehension builds a new list from an old one in a single expression: square brackets around an expression, a for clause and an optional if clause. Step through big = [n * 10 for n in nums if n > 2] one item at a time: watch for take each value, if test it, and the expression turn the ones that pass into new items, so the new list grows to [40, 50]. Then see the same work written as a plain for loop.

12 min10 steps5 questionsBeginner
Fig 9 · Interactive
Loading figure…
or ← →

Quiz Unlocks after the last step.