List Comprehensions
Lesson 5 of 6 · View course roadmap
Learn the idea
Comprehensions build lists in a single expressive line — Python's signature feature:
[x * 2 for x in nums]— transform every item[x for x in nums if x > 0]— filter items[x * 2 for x in nums if x > 0]— filter and transform
Read it as: "give me x * 2, for each x in nums, if x > 0". They replace 4-line loop-and-append patterns with one clear line.
Dict comprehensions work too: {w: len(w) for w in words}. Keep comprehensions simple — if it needs two ifs and nesting, use a normal loop.
Where you'll use this
Comprehensions are the mark of fluent Python — code reviewers at top companies flag 4-line append loops that should be one comprehension. They also map directly onto SQL's SELECT-WHERE mental model.
Common mistakes
- Nesting too much: a comprehension with multiple
fors andifs is harder to read than the loop it replaced. Two clauses max. - Using one for side effects:
[print(x) for x in items]builds a useless list of Nones — use a plain loop when you don't need the result. - Filter goes after the for:
[x if x > 0 for x in nums]is a SyntaxError;[x for x in nums if x > 0]is right. (x if cond else y before the for is a different, valid pattern.)
Pro tip
Generator expressions — the same syntax with () — process items lazily without building a list: sum(n * n for n in range(10**6)) uses almost no memory.
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Using one list comprehension, build a list of the cubes of the odd numbers from 1 to 9, and print it. Expected: [1, 27, 125, 343, 729]
[1, 27, 125, 343, 729]
[n ** 3 for n in range(1, 10) if n % 2 == 1]
cubes = [n ** 3 for n in range(1, 10) if n % 2 == 1] print(cubes)
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.