A comprehension is a short, readable way to build a new list, dictionary, or set from an existing iterable in a single expression. Instead of creating an empty list and calling append() inside a for loop, you describe the result you want: [n * n for n in numbers].
In this tutorial, you’ll learn the syntax of list, dictionary, and set comprehensions, how to filter and transform items, how nested comprehensions work, how generator expressions save memory, and when a regular loop is the better choice.
Key terms used in this article:
- Comprehension: An expression that builds a collection from an iterable, such as
[x * 2 for x in data]. - Iterable: Anything you can loop over: a list, tuple, string, range, dictionary, set, file, and so on.
- Expression: The part at the start of a comprehension that produces each new item.
- Filter condition: An optional
ifclause that decides which items to keep. - Generator expression: A comprehension in parentheses that produces items lazily, one at a time.
Table of contents
- Why use comprehensions?
- List comprehensions
- Nested loops in comprehensions
- Dictionary comprehensions
- Set comprehensions
- Generator expressions
- Using the walrus operator in comprehensions
- Variable scope in comprehensions
- Performance: comprehensions vs. loops
- When not to use a comprehension
- Comprehension cheat sheet
- Common mistakes
- Practice exercises
- Summary
Why use comprehensions?
Here’s the same task, squaring the numbers from 1 to 5, written with a loop and with a list comprehension:
Output:
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
Comprehensions are shorter, they make the purpose (building a new collection) obvious at a glance, and they usually run faster than the equivalent loop with append().
List comprehensions
List comprehension syntax
Read it from the middle: “for each item in iterable, evaluate expression, and collect the results in a list.”
Output:
['Jessa', 'Kelly', 'Emma'] [11.8, 30.09, 47.2] [6, 5, 6, 3] ['a', 'b', 'c']
Filtering with if
Add an if clause at the end to keep only the items that pass a test:
Output:
[8, 22, 40] [225, 484, 1600] ['apple', 'banana', 'cherry']
You can chain several if clauses. They work like and:
Output:
[0, 15, 30, 45] [0, 15, 30, 45]
Transforming with if-else
To change each item depending on a condition (instead of dropping items), put a conditional expression at the beginning:
Output:
['odd', 'even', 'odd', 'even', 'odd'] [3, 8, 10, 10, 7]
Where does the if go? [x for x in data if condition] filters items, so the result can be shorter. [a if condition else b for x in data] transforms every item, so the result has the same length. An if at the end can’t have an else.
You can combine both forms:
Output:
['fail', 'pass', 'pass', 'pass']
Calling functions in a comprehension
Output:
[32.0, 70.7, 98.6, 212.0] [42, 7, 19]
Nested loops in comprehensions
A comprehension can have several for clauses. They run in the same order as nested for loops written out normally:
Output:
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
Flattening a list of lists
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Read it as: “for each row in matrix, for each num in row, collect num.”
Nested comprehensions: building a matrix
A comprehension inside another comprehension’s expression creates nested lists:
Output:
[1, 2, 3] [2, 4, 6] [3, 6, 9] [[1, 4], [2, 5], [3, 6]]
The outer comprehension builds the rows, and the inner one builds the values in each row. For transposing, list(zip(*matrix)) is a shorter alternative.
Dictionary comprehensions
Dictionary comprehension syntax
Output:
{'jessa': 5, 'kelly': 5, 'emma': 4}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{'name': 'Jessa', 'age': 28, 'city': 'London'}
Transforming and filtering an existing dictionary
Loop over items() to work with both keys and values:
Output:
{'apple': 1.08, 'mango': 2.25, 'banana': 0.45, 'cherry': 2.7}
{'apple': 1.2, 'mango': 2.5, 'cherry': 3.0}
{'APPLE': 1.2, 'MANGO': 2.5, 'BANANA': 0.5, 'CHERRY': 3.0}
Swapping keys and values
Output:
{'India': 'IN', 'France': 'FR', 'Japan': 'JP'}
If several keys share the same value, later items overwrite earlier ones, because dictionary keys must be unique.
Grouping and counting
Output:
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
{'i': 4, 'm': 1, 'p': 2, 's': 4}
These examples are readable, but they scan the list once per key. For large data, collections.Counter and defaultdict are faster.
Set comprehensions
A set comprehension uses curly braces without a colon. The result is a set, so duplicates are removed automatically:
Output:
['apple', 'banana', 'cherry'] [1, 2, 3] ['gmail.com', 'yahoo.com']
Sets are unordered, so sorted() is used here to display the results in a predictable order.
Note that {} on its own creates an empty dictionary, not a set. Use set() for an empty set.
Generator expressions
Use parentheses instead of square brackets to create a generator expression. It produces items one at a time, only when they’re needed, instead of building a full list in memory:
Output:
True True 333332833333500000
When a generator expression is the only argument of a function, you can drop the extra parentheses:
Output:
25 13 True PYTHON, COMPREHENSION, IS, NEAT
A generator can only be used once. After it’s exhausted, it produces nothing:
Output:
[0, 1, 2] []
There’s no tuple comprehension. To build a tuple, pass a generator expression to tuple(): tuple(n * 2 for n in range(3)).
Using the walrus operator in comprehensions
The assignment expression := (Python 3.8+) lets you compute a value once and use it in both the filter and the result:
Output:
[6, 15]
Without :=, you’d have to call expensive(n) twice.
Variable scope in comprehensions
The loop variable in a comprehension is local to the comprehension. It doesn’t leak into or overwrite the surrounding code:
Output:
original
Performance: comprehensions vs. loops
List comprehensions are usually faster than building a list with append() in a loop, because they avoid repeated method lookups:
Run it to compare on your own machine. The exact times depend on your computer and Python version, and the comprehension is usually the faster of the two. Still, choose comprehensions for readability first. The speed difference only matters in hot code paths.
When not to use a comprehension
Comprehensions are for building collections. Use a regular for loop when:
- You only want side effects, such as printing or writing to a file.
[print(x) for x in items]builds a useless list ofNonevalues. - The logic is complex. More than two
forclauses, or long conditions, are hard to read. Split them into a loop or a helper function. - You need statements such as
try/except,break, or multiple assignments.
Output:
[(0, 1), (0, 2), (2, 3)] [(0, 1), (0, 2), (2, 3)]
Comprehension cheat sheet
| Type | Syntax | Result |
|---|---|---|
| List | [x * 2 for x in data] | list |
| List with filter | [x for x in data if x > 0] | list (possibly shorter) |
| List with if-else | [x if x > 0 else 0 for x in data] | list (same length) |
| Nested loops | [x * y for x in a for y in b] | list |
| Dictionary | {k: v for k, v in pairs} | dict |
| Set | {x % 3 for x in data} | set |
| Generator | (x * 2 for x in data) | generator (lazy) |
Common mistakes
- Putting
elsewith a filter at the end.[x for x in data if x > 0 else 0]is aSyntaxError. Move the conditional expression to the front. - Reversing the order of nested
forclauses. Write them in the same order as nested loops: outer loop first. - Using
{}for an empty set. That’s an empty dictionary. - Reusing an exhausted generator. Convert it to a list if you need the items more than once.
- Writing comprehensions just for side effects. Use a normal loop.
Practice exercises
Exercise 1: Create a list of all numbers from 1 to 30 that are divisible by 3 but not by 2.
Output:
[3, 9, 15, 21, 27]
Exercise 2: Given a sentence, build a dictionary that maps each word to its length, skipping words shorter than 3 characters.
Output:
{'Comprehensions': 14, 'Python': 6, 'are': 3, 'neat': 4, 'and': 3, 'fast': 4, 'tool': 4}
Exercise 3: Flatten a list of lists and keep only the unique values, sorted.
Output:
[1, 2, 3, 4, 5]
Exercise 4: From a dictionary of students and scores, build a dictionary that maps each student to “pass” or “fail” (pass mark 50).
Output:
{'Jessa': 'pass', 'Kelly': 'fail', 'Emma': 'pass'}
Summary
- A comprehension builds a new collection from an iterable in one readable expression.
- List:
[expr for x in data]. Dictionary:{k: v for x in data}. Set:{expr for x in data}. - An
ifat the end filters items. A conditional expression at the start transforms every item. - Several
forclauses work like nested loops, in the same order. - Generator expressions,
(expr for x in data), produce items lazily and save memory. Pass them directly tosum(),max(),any(), andjoin(). - Use comprehensions to build collections, and regular loops for side effects or complex logic.
Also, See:

Leave a Reply