List, Dict & Set Comprehensions
Building a new collection from an old one — squaring numbers, filtering out bad rows, flipping a dictionary — is something you'll do dozens of times a day. Comprehensions turn that three-line loop into one expressive, readable line.
Learn List, Dict & Set Comprehensions in our free Python course — a beginner-friendly interactive lesson with runnable examples, a practice exercise and a…
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
They're one of the most loved features of Python. Master the pattern once and it works for lists, dicts, sets, and generators alike.
Start with the loop you already know, then watch it collapse into one line. They produce the identical result:
Read it left to right: "Give me n squared , for each n in this range." The expression comes first, the source loop second.
Add an if at the end to keep only the items you want. This is the filter pattern, and it's incredibly common:
The trailing if decides whether an item is included. The expression at the front decides what it looks like. You can use either or both.
When you want to change every item based on a condition (not drop any), the conditional expression moves to the front:
Same idea, but you produce key: value pairs inside curly braces. Perfect for building lookups or flipping dictionaries:
Notice .items() gives you both the key and value to work with — and that pair is unpacked exactly like the tuples from the last lesson.
Set comprehension — unique results automatically
Swap the square brackets for round ones and Python produces items one at a time instead of building the whole list. Great for huge data or feeding a function:
These lines should build a dictionary of passing students and print how many there are. Reorder them so the output is Passing: 2 .
Why: the scores dict (B) must exist before the comprehension (A) can iterate over .items() . Defining PASS (D) first keeps the threshold documented at the top. Only Ada (88) and Cleo (71) clear 60, so the count is 2.
[0, 2, 4, 6] — range(4) yields 0,1,2,3 and each is doubled.
[1, 3] — x % 2 is truthy (1) for odd numbers and falsy (0) for even, so only odds pass the filter.
{' '} — a set comprehension collects unique lengths: "hi" and "yo" are 2, "hey" is 3, and the duplicate 2 collapses.
Use comprehensions to clean a sentence and build a length lookup.
Lesson complete — you write Pythonic code now!
You can collapse loops into list, dict, and set comprehensions, filter with a trailing if , transform with a leading if/else , and reach for a generator when memory matters. This is some of the most idiomatic Python there is.
🚀 Up next: *args & **kwargs — write functions that accept any number of arguments.
Practice quiz
What does [n ** 2 for n in range(1, 6)] produce?
It squares each n from 1 to 5: [1, 4, 9, 16, 25].
In a comprehension, where does a FILTERING if go?
- At the front
- At the end (trailing)
- It can't be used
- In the middle
Answer: At the end (trailing). A trailing if, e.g. [x for x in items if x > 0], filters which items are kept.
What does [x for x in [1, 2, 3, 4] if x % 2] produce?
x % 2 is truthy for odd numbers, so only the odds 1 and 3 pass.
When you need an if/else that transforms EVERY item, where does it go?
- At the end
- At the front (leading)
- It is not allowed
- After the for
Answer: At the front (leading). A leading if/else, e.g. [x if cond else y for x in items], transforms every item without dropping any.
Which brackets build a dictionary comprehension?
Dict comprehensions use curly braces with key: value pairs, e.g. {k: v for ...}.
What does {n: n ** 2 for n in range(1, 4)} create?
- {1: 1, 2: 4, 3: 9}
Answer: {1: 1, 2: 4, 3: 9}. It maps each n to its square in a dictionary: {1: 1, 2: 4, 3: 9}.
What does a set comprehension like {len(w) for w in ['hi', 'yo', 'hey']} give?
- {2, 2, 3}
- {2, 3}
Answer: {2, 3}. Set comprehensions keep unique results: lengths 2 (hi, yo) and 3 (hey) collapse to {2, 3}.
Which brackets create a generator expression?
Generator expressions use round parentheses, e.g. (x*x for x in r).
Why use a generator expression over a list comprehension for huge data?
- It is sorted
- It produces items lazily, using little memory
- It is always faster to index
- It removes duplicates
Answer: It produces items lazily, using little memory. A generator yields items one at a time instead of building the whole list, saving memory.
What does [x * 2 for x in range(4)] produce?
range(4) is 0,1,2,3 and each is doubled: [0, 2, 4, 6].