Python Comprehensions: List, Set, and Dictionary Syntax
Python comprehensions are a short, readable way to build new lists, sets, and dictionaries from existing data. They replace many simple for loops and append calls with one expression, while still keeping the logic clear when used well. This article shows how comprehensions work, when to use each kind, and the mistakes that trip people up.
Difficulty: Beginner
Helpful to know first: Basic Python syntax, for loops, and how lists, sets, and dictionaries store values.
How Python Comprehensions Build New Collections
A comprehension is an expression that creates a collection by looping over another iterable and optionally filtering items. The main idea is simple: instead of writing a loop that starts with an empty collection and adds items one by one, you describe the result directly.
For a list comprehension, Python uses square brackets. For a set comprehension, it uses curly braces. For a dictionary comprehension, it uses curly braces with a key and value separated by a colon.
Here is the smallest useful list comprehension:
numbers = [1, 2, 3, 4]
squares = [number * number for number in numbers]
print(squares) # Output: [1, 4, 9, 16]Python reads this as: take each number from numbers, square it, and store the result in a new list. The original list does not change.
A comprehension is still a loop. It is just written as an expression, so it can appear where Python expects a value.
List Comprehensions for Everyday Data Cleanup
List comprehensions are the most common kind. They are a good fit when you want a new list from an old one and the transformation is small.
Turning strings into cleaned values
Suppose you have user input with extra spaces. A comprehension can strip each item and keep only the cleaned values.
names = [" Ada ", " grace", "LINUS "]
cleaned = [name.strip() for name in names]
print(cleaned) # Output: ['Ada', 'grace', 'LINUS']The expression before for runs once for every item. Because the result is a new list, the original names list stays unchanged.
Filtering only the values you want
You can add an if clause to keep only some items. This is the same idea as an if statement inside a loop, but written in a compact form.
numbers = [1, 2, 3, 4, 5]
evens = [number for number in numbers if number % 2 == 0]
print(evens) # Output: [2, 4]The condition comes at the end. Only values that make the condition true are included in the new list.
Replacing a small loop
The same work can be written with a loop. This version is longer, but it can be easier to read when you are first learning.
numbers = [1, 2, 3, 4, 5]
evens = []
for number in numbers:
if number % 2 == 0:
evens.append(number)
print(evens) # Output: [2, 4]The list comprehension does the same job in one expression. The loop version is often better when the process has several steps or needs extra debugging output.
Set and Dictionary Comprehensions for Unique Values and Lookup Tables
Sets and dictionaries use the same idea, but they solve different problems. A set comprehension creates unique values. A dictionary comprehension creates key-value pairs.
Using a set comprehension to remove duplicates
If you only care about unique items, a set comprehension is a good fit. The braces look similar to a dictionary, but there is no colon.
words = ["cat", "dog", "cat", "bird"]
unique_lengths = {len(word) for word in words}
print(unique_lengths) # Output: {3, 4}Because sets store only unique values, duplicate lengths are removed automatically. The order of items in a set is not something you should rely on.
Building a dictionary from two pieces of information
A dictionary comprehension is useful when you need to compute values or transform data into a lookup table.
names = ["ada", "grace", "linus"]
name_lengths = {name: len(name) for name in names}
print(name_lengths) # Output: {'ada': 3, 'grace': 5, 'linus': 5}The key goes before the colon and the value goes after it. Each item in the output dictionary comes from one item in the input sequence.
Using a dictionary comprehension to flip keys and values
Sometimes you already have a dictionary and want a new one with different keys. This is common when the values are unique.
student_ids = {"Ada": 101, "Grace": 102}
ids_to_names = {student_id: name for name, student_id in student_ids.items()}
print(ids_to_names) # Output: {101: 'Ada', 102: 'Grace'}This works because dict.items() gives you pairs to unpack. If two names shared the same ID, the later one would overwrite the earlier one.
How Comprehensions Evaluate Each Part
Comprehensions are compact, but the order of evaluation matters. Python processes them left to right for the loop part, then applies the condition, then computes the expression for the items that pass.
That order matters when the expression has a function call or a side effect.
def make_label(number):
print(f"making {number}")
return f"item-{number}"
labels = [make_label(number) for number in [1, 2] if number > 1]
print(labels)
# Output:
# making 2
# ['item-2']The function is called only for values that pass the condition. The item 1 is skipped before make_label runs.
Multiple for clauses also work. They behave like nested loops.
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]
print(pairs) # Output: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]Read nested comprehensions carefully from left to right. The last loop changes fastest, just like nested for loops.
A comprehension should stay simple enough to read at a glance. If you need several conditions, helper functions, or nested logic, a regular loop is often clearer.
When Comprehensions Are Fast Enough and When They Are Not
Comprehensions are usually efficient because Python implements them in optimized bytecode and they avoid repeated method lookups like append inside a loop. For small and medium tasks, the difference usually does not matter much, but comprehensions are often both shorter and at least as fast as the equivalent loop.
They do not magically make expensive work cheap. If each item needs database access, file I/O, or a slow network call, the comprehension is not the performance bottleneck. The cost comes from the work inside it.
Another important detail is memory use. A list comprehension builds the whole list in memory right away. If you need to process a large stream of data one item at a time, a generator expression may be a better choice.
numbers = range(5)
squares_list = [number * number for number in numbers]
squares_gen = (number * number for number in numbers)
print(squares_list) # Output: [0, 1, 4, 9, 16]
print(list(squares_gen)) # Output: [0, 1, 4, 9, 16]The list comprehension creates the full list immediately. The generator expression creates values lazily, one at a time, which is better for very large data.
Predict the Output
Predict the output of a filtered comprehension
What does this print?
values = [1, 2, 3, 4]
result = [value * 10 for value in values if value > 2]
print(result)Show answer
It prints [30, 40]. Python checks each value first. Only 3 and 4 pass the condition, so only those values are multiplied by 10 and added to the result list.
Predict the output of nested loops in a comprehension
What does this print?
pairs = [(x, y) for x in range(2) for y in "ab"]
print(pairs)Show answer
It prints [(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]. The first loop chooses 0, then the second loop runs through both letters. Then the first loop moves to 1 and the second loop runs again.
Common Mistakes
Using the wrong brackets for the kind of comprehension
Each comprehension type uses a different bracket pattern. List comprehensions use square brackets, set comprehensions use braces without a colon, and dictionary comprehensions use braces with a colon.
Problem: This code tries to make a dictionary but forgets the key-value colon, so Python cannot parse it as a dictionary comprehension.
words = ["a", "bb"]
lengths = {word for word in words}
print(lengths)Fix: Use a list comprehension if you want a list, or add a colon if you want a dictionary.
words = ["a", "bb"]
lengths = [len(word) for word in words]
print(lengths) # Output: [1, 2]The corrected version works because the brackets now match the kind of collection being built.
Putting the condition in the wrong place
The if clause belongs at the end of a comprehension, not before the expression.
Problem: This code looks like a loop with a filter, but the syntax is wrong for a comprehension.
numbers = [1, 2, 3]
evens = [if number % 2 == 0 number for number in numbers]
print(evens)Fix: Put the filter after the loop part.
numbers = [1, 2, 3]
evens = [number for number in numbers if number % 2 == 0]
print(evens) # Output: [2]The corrected version works because Python reads the loop first and then applies the filter.
Expecting a comprehension to modify the original collection
A comprehension creates a new collection. It does not change the one you loop over.
Problem: This code builds doubled values, but the original list remains unchanged because the result is never assigned back.
numbers = [1, 2, 3]
[number * 2 for number in numbers]
print(numbers) # Output: [1, 2, 3]Fix: Save the new list in a variable if you want to use it later.
numbers = [1, 2, 3]
doubled = [number * 2 for number in numbers]
print(doubled) # Output: [2, 4, 6]The corrected version works because the new list is stored and used directly.
Putting too much logic inside one line
Comprehensions are short, but they can become hard to read if they do too much work at once.
Problem: This expression is difficult to scan because it mixes formatting, filtering, and branching in one line.
values = [1, 2, 3, 4]
labels = ["even" if value % 2 == 0 else "odd" for value in values]
print(labels) # Output: ['odd', 'even', 'odd', 'even']Fix: Move complex logic into a helper function or use a normal loop if readability is better.
def label_value(value):
if value % 2 == 0:
return "even"
return "odd"
values = [1, 2, 3, 4]
labels = [label_value(value) for value in values]
print(labels) # Output: ['odd', 'even', 'odd', 'even']The corrected version works because the comprehension stays simple and the branching lives in a named function.
Find the Bug
Find the bug in this code that is meant to collect the lengths of non-empty names.
names = ["Ada", "", "Grace"]
lengths = [len(name) for name in names if len(name) > 0]
print(lengths) # Output: [3, 5]Show answer
The bug is subtle: this code works, but it repeats len(name) twice, which is unnecessary. For simple strings that does not matter much, but with an expensive function call it would be wasteful. A clearer version filters by the string itself and computes the length once for each kept item.
names = ["Ada", "", "Grace"]
lengths = [len(name) for name in names if name]
print(lengths) # Output: [3, 5]The fixed version is easier to read because the condition checks whether the string is non-empty directly.
When to Use a Comprehension and When to Use a Loop Instead
Use a comprehension when you are creating a new collection with a simple pattern. Use a regular loop when the logic is long, when you need multiple statements per item, or when the steps need names to stay readable.
| Situation | Better choice | Why |
|---|---|---|
| Build a list of transformed values | Comprehension | Short, clear, and direct |
| Filter items and transform them once | Comprehension | Fits the expression style |
| Several steps per item | Loop | Easier to debug and read |
| Need to log, break, or continue in complex ways | Loop | More flexible control flow |
| Need lazy evaluation for large data | Generator expression | Uses less memory |
A common alternative is map() or filter(). They can be useful, but comprehensions are usually easier to read in Python code. For most beginners and many intermediate tasks, the comprehension is the clearer choice.
Comprehension versus map() and filter()
map() and filter() can solve the same problems, but they often hide the logic inside function objects. A comprehension keeps the transformation and filtering in one visible expression.
numbers = [1, 2, 3, 4]
squares = [number * number for number in numbers]
squares_map = list(map(lambda number: number * number, numbers))
print(squares)
print(squares_map) # Output: [1, 4, 9, 16]Both versions work. The comprehension is usually preferred because it reads like the result you want instead of a function pipeline.
Common Interview Questions About Python Comprehensions
What is the difference between a list comprehension and a generator expression?
A list comprehension builds the whole list immediately. A generator expression produces values one at a time and does not store the full result unless you convert it to a list or consume it in a loop.
Can a comprehension have more than one for clause?
Yes. Multiple for clauses work like nested loops. The rightmost loop runs fastest.
When should you avoid a comprehension?
Avoid one when the logic is too complex to read comfortably. If the expression starts to feel like a puzzle, a regular loop is usually the better choice.
Try It Yourself
Write a list comprehension that:
- Starts with numbers = [1, 2, 3, 4, 5, 6]
- Keeps only the even numbers
- Doubles each kept number
- Prints the resulting list
Expected output:
[4, 8, 12]Hint: Put the filter at the end of the comprehension, and put the multiplication before the for clause.
Show solution
numbers = [1, 2, 3, 4, 5, 6]
result = [number * 2 for number in numbers if number % 2 == 0]
print(result) # Output: [4, 8, 12]Summary
- Comprehensions build new lists, sets, and dictionaries from existing iterables.
- List comprehensions use [], set comprehensions use {}, and dictionary comprehensions use {key: value}.
- The loop part comes first in the syntax, and the filter if comes at the end.
- Comprehensions are great for short transformations and filters, but not for complicated logic.
- They create new collections; they do not modify the original iterable.
- For large data or lazy processing, a generator expression may be a better choice.
If you want the next topic to study, look at generator expressions. They use a similar syntax, but they return values lazily instead of building a full list at once.