Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

List Comprehensions

14 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 5 of 6 · View course roadmap
Step 1

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 and ifs 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.

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +30 XP

Blank · autosaved

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]

Target output
[1, 27, 125, 343, 729]
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What does [c.upper() for c in 'abc'] produce?
2. Where does the if filter go in a comprehension?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path