List Comprehensions
- Write list comprehensions to replace verbose
forloops - Filter items with conditional expressions inside comprehensions
- Nest comprehensions for 2D data
- Recognize when a comprehension hurts readability
Comprehensions are the idiomatic Python filter/map — libraries like pandas, Django ORM chains, and FastAPI dependency wiring lean on them for readable one-pass transforms. Reviewers reject for loops that append to a list when a comprehension fits.
- Nesting three levels deep for cleverness — split into a helper or a real
forloop once readability drops. - Building a huge list just to iterate once — swap
[...]for a generator(...)to avoid the memory spike. - Late-binding closures inside
lambda x: ...comprehensions — bind withlambda x, v=v: ...explicitly.
[expr for x in seq if cond] — read it left to right.
Why bother
- One line, clear intent, faster than
for+.append() - Works for dicts (
{k: v for ...}) and sets ({x for ...}) too
When NOT to
- If the expression is complex, write the loop. Readability > cleverness.
- If you don't need the list (just want side effects), use a regular loop.
Try it
- Build a list of
(word, len(word))for words longer than 4 letters. - Convert
[1, 2, None, 3, None, 4]into[1, 2, 3, 4].
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Using a list comprehension, build a list of the squares of numbers 1 through 5, then print it. Expected:
[1, 4, 9, 16, 25]. - Exercise 2
From
nums = [4, 7, 1, 8, 2, 9, 3], use a list comprehension with a filter to keep only even numbers, then print the result. Expected:[4, 8, 2]. - Exercise 3
From
words = ["apple", "kiwi", "banana", "fig", "mango"], build a list of the UPPERCASED words that have length ≤ 4, then print it. Expected:['KIWI', 'FIG'].