From Loops to Readable Comprehensions
Unit ID: M04-U07 Estimated active time: 20-30 minutes
Begin with the expanded form
raw_titles = [" values ", " collections ", " loops "]
clean_titles = []
for title in raw_titles:
clean_title = title.strip().title()
clean_titles.append(clean_title)
You can explain every step: take an item, transform it, and append the result.
The equivalent list comprehension
clean_titles = [title.strip().title() for title in raw_titles]
Read it as:
Create a list containing the cleaned title for each title in raw titles.
Use a comprehension only when that sentence remains easy to say.
Add one simple filter
Expanded form:
valid_hours = []
for value in [8, -2, 12]:
if value >= 0:
valid_hours.append(value)
Comprehension:
valid_hours = [value for value in [8, -2, 12] if value >= 0]
Know when not to compress
Keep an ordinary loop when you need:
- several validation reasons;
- multiple outputs;
- logging or explanation;
breakorcontinue;- several state updates; or
- nested conditions that are difficult to read.
The module checkpoint requires an ordinary loop because accepted records, rejected records, reasons, and totals all matter.
Practice
Write ordinary loops first, then comprehensions for:
- doubling
[2, 4, 6]; - cleaning
[' ai ', ' python ']; - selecting non-empty strings from
['AI', '', 'Python'].
Compare outputs and explain why the source collections remain unchanged.
Takeaway
A comprehension is a concise expression for one clear collection transformation or filter. If the expanded loop is not understood, compression hides the logic. Next, we will test the edge cases that expose weak conditions.
