Python Comprehensions: List, Dict, Set, and Generator in One Guide
Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.
Comprehensions are one of Python's most loved features. They let you create new lists, dictionaries, and sets by describing what you want instead of writing step-by-step instructions for how to build it.
In this tutorial, you'll learn all four types of comprehensions — list, dict, set, and generator — along with filtering, conditionals, and the important question of when NOT to use them.
List Comprehensions — The Most Common Pattern
A list comprehension creates a new list by applying an expression to each item in an existing sequence. The syntax is: [expression for item in iterable].
Think of it as a compact for loop that builds a list. Instead of creating an empty list and appending inside a loop, you describe the result in a single line.
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25]Adding Conditions to Comprehensions
You can add an if clause to filter out items. Only items that pass the condition get included in the new list. The syntax is: [expression for item in iterable if condition].
You can also use an if-else expression to transform items differently based on a condition. But notice the syntax change — the if-else goes before the for, not after it.
Dict Comprehensions
Dict comprehensions work just like list comprehensions, but they create dictionaries. Use curly braces and a key: value expression. The syntax is: {key: value for item in iterable}.
You can also filter with if, just like list comprehensions. This is great for creating a subset of a dictionary.
Set Comprehensions
Set comprehensions create sets — collections with no duplicates. The syntax uses curly braces just like dict comprehensions, but without the colon. The syntax is: {expression for item in iterable}.
The key difference from list comprehensions is that sets automatically remove duplicates. Even though "Alice" and "Anna" both start with "A", the set only contains one "A".
Generator Expressions — Memory-Efficient Comprehensions
A generator expression looks like a list comprehension but uses parentheses instead of brackets. The big difference: it doesn't create all items at once. It generates them one at a time, on demand.
This matters when you're working with very large data. A list comprehension of a million items creates a million-item list in memory. A generator expression uses almost no memory — it computes each item only when you ask for it.
Generator expressions are commonly used inside functions like sum(), max(), and min(). You can skip the extra parentheses when the generator is the only argument.
Nested Comprehensions
You can put one for clause inside another to handle nested loops. The outer loop comes first, then the inner loop. This is useful for flattening lists or creating grids.
When NOT to Use Comprehensions
Comprehensions are powerful, but they're not always the right choice. If a comprehension is hard to read, a regular loop is better. Code clarity always wins over cleverness.
Avoid comprehensions when: the logic is complex with multiple conditions, you need side effects like printing inside the loop, or the comprehension spans more than about 80 characters wide.
result = [x * 2 if x > 0 else -x for x in data
if x != 0 and x % 3 == 0]result = []
for x in data:
if x != 0 and x % 3 == 0:
if x > 0:
result.append(x * 2)
else:
result.append(-x)Also, never use a comprehension purely for side effects. If you're calling print() or modifying an external variable, use a regular loop instead. A comprehension should always be about building a new collection.
Practice Exercises
Time to practice! These exercises cover all four comprehension types, from basic to more challenging patterns.
Use a list comprehension to create a list called doubled that contains each number from the given list, multiplied by 2.
Expected output:
[2, 4, 6, 8, 10]Use a list comprehension with an if clause to create a list called evens that contains only the even numbers from the given list.
Expected output:
[4, 12, 8, 20, 6]Read this code carefully and predict what it will print. Pay attention to where the if-else is placed.
Type the exact output.
Use a dict comprehension to create a dictionary called name_lengths that maps each name to its length.
Expected output:
{'Alice': 5, 'Bob': 3, 'Charlie': 7}Use a set comprehension to find all unique vowels in the given word. Store the result in a variable called vowels_found, then print it sorted as a list.
Expected output:
['a', 'e', 'i', 'o']This code tries to create a list where numbers above 5 are labeled 'high' and others are labeled 'low'. But the syntax is wrong and it crashes. Fix it.
Expected output:
['low', 'high', 'low', 'high', 'low', 'high']Refactor the following loop into a single list comprehension. The output must stay exactly the same.
Expected output:
[1, 9, 25, 49, 81]Use a list comprehension with two for clauses to flatten the given matrix (a list of lists) into a single flat list. Then print the sum of all items using a generator expression inside sum().
Expected output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
45Summary: What You Learned About Python Comprehensions
| Here's a recap of everything you now know: | ||
|---|---|---|
| --- | --- | --- |
| List comprehension | [expr for x in items] | A list |
| Filtered list | [expr for x in items if cond] | Filtered list |
| Transformed list | [a if cond else b for x in items] | Mapped list |
| Dict comprehension | {k: v for x in items} | A dict |
| Set comprehension | {expr for x in items} | A set (no dupes) |
| Generator expression | (expr for x in items) | A lazy generator |
| Nested comprehension | [expr for a in X for b in a] | Flattened list |
Comprehensions are one of Python's signature features. They make your code shorter, more readable (when used well), and often faster than equivalent loops.
What's Next?
Now that you can create and transform collections with ease, you're ready to explore [Python Tuples](/python/python-tuples) — immutable sequences that are perfect for fixed data like coordinates, records, and function return values.
You'll learn why immutability is useful, how tuple packing and unpacking work, and when to choose a tuple over a list.