List, Dict, and Set Comprehensions
Scenario: A status report must filter healthy services and transform their names.
New words, in plain English
- Comprehension - compact syntax that builds a collection from an iterable
- Expression - the value produced for each selected item
- Filter clause - an optional
ifdeciding which items enter
Read [expression for item in source if condition] from left to right. Dict comprehensions produce key-value pairs; set comprehensions remove duplicates.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
codes = [200, 503, 204]
healthy = [code for code in codes if code < 400]
labels = {code: "ok" for code in healthy}
unique = {code // 100 for code in codes}
Tip: Use a normal loop when the comprehension needs side effects or becomes hard to read.
Goal: Practice this idea in the py-list-comprehension challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.