List, Dict, and Set Comprehensions
Master Python comprehensions—the elegant, concise, and fast way to transform, filter, and create lists, dictionaries, and sets in a single readable line.
Consider a very common programming task: take a list of numbers, filter out the odd numbers, and square the remaining even numbers.
In most programming languages, you would write this with four lines of boilerplate code:
# The traditional, verbose approach
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = []
for n in numbers:
if n % 2 == 0:
even_squares.append(n ** 2)
print(even_squares) # [4, 16, 36, 64, 100]
This works, but it feels clumsy. You had to create an empty list, write a loop, check an if condition, and manually call .append() on every single match.
Python offers a cleaner, more readable, and faster alternative borrowed from mathematical set notation: Comprehensions.
# The Pythonic comprehension:
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
In a single expressive line, your intent is crystal clear: “Give me the square of n for every n in numbers where n is even.”
1. Anatomy of a List Comprehension
Every list comprehension follows this core formula:
[ expression for item in iterable if condition ]
│ │ │
What to keep? Where does it come Which ones
(Transformation) from? qualify?
1. Simple Transformation (Mapping)
Convert or calculate values for every element:
names = ["alice", "bob", "charlie"]
# Capitalize every name
clean_names = [name.title() for name in names]
print(clean_names) # ['Alice', 'Bob', 'Charlie']
# Convert USD to EUR (at 0.92 exchange rate)
prices_usd = [10.0, 25.5, 99.0]
prices_eur = [round(price * 0.92, 2) for price in prices_usd]
print(prices_eur) # [9.2, 23.46, 91.08]
2. Filtering Elements
Use the trailing if to discard unwanted items:
scores = [88, 42, 95, 61, 74, 55, 99]
# Keep only passing grades (70 or higher)
passing_scores = [score for score in scores if score >= 70]
print("Passing:", passing_scores) # [88, 95, 74, 99]
2. The Conditional Dilemma: if vs if-else
One of the most frequent points of confusion for learners is where to place an if statement in a comprehension.
Pattern A: Filtering (at the end)
Use if at the end when you want to filter out items completely:
# Only keep positive numbers:
nums = [-5, 12, -3, 8, 0]
positives = [x for x in nums if x > 0]
print(positives) # [12, 8]
Pattern B: Transformation with if-else (at the front)
Use ternary if ... else before the for keyword when you want to keep every item, but transform its value conditionally:
# Label every number as 'Even' or 'Odd':
nums = [1, 2, 3, 4, 5]
labels = ["Even" if x % 2 == 0 else "Odd" for x in nums]
print(labels) # ['Odd', 'Even', 'Odd', 'Even', 'Odd']
3. Set Comprehensions
Just as square brackets [...] produce a list, curly braces {...} with a single expression produce a set.
Set comprehensions automatically discard duplicate values and create a unique collection in one step:
raw_tags = ["python", "Django", "PYTHON", "fastapi", "django"]
# Clean and deduplicate tags in a single line
unique_tags = {tag.lower() for tag in raw_tags}
print(unique_tags)
Output:
{'python', 'django', 'fastapi'}
Notice that "django" and "python" were deduplicated automatically!
4. Dictionary Comprehensions
Dictionary comprehensions also use curly braces {...}, but you provide a key: value pair before the for statement:
words = ["apple", "banana", "cherry", "date"]
# Create a mapping from each word to its character length
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Output:
{'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}
Inverting a Dictionary
A classic Python trick: flip keys and values using a dict comprehension:
original = {"a": 1, "b": 2, "c": 3}
inverted = {value: key for key, value in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
Filtering Dictionaries
stock = {"laptops": 15, "monitors": 0, "keyboards": 4, "mice": 0}
# Keep only items currently in stock
in_stock = {item: qty for item, qty in stock.items() if qty > 0}
print(in_stock) # {'laptops': 15, 'keyboards': 4}
5. Performance: Why Comprehensions Are Faster
Comprehensions are not just syntactic sugar; they are measurably faster than regular for loops appending to an empty list.
In a normal loop:
# In every single iteration, Python has to:
# 1. Look up the attribute 'append' on the list object
# 2. Call the function
# 3. Push and pop a function call frame
In a comprehension:
CPython runs a dedicated internal C-level bytecode instruction (LIST_APPEND) directly inside the virtual machine loop. It skips the attribute lookup and method call overhead entirely!
6. The Golden Rule: Readability Counts
The Zen of Python states: “Simple is better than complex” and “Readability counts”.
While you can nest multiple loops inside a comprehension:
# Technically legal, but hard to read:
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row] # [1, 2, 3, 4, 5, 6]
If your comprehension grows to multiple lines, contains complex logic, or makes someone pause to decipher what it is doing:
Stop and write a regular
forloop!
A readable 3-line loop is always superior to a clever, unreadable 1-line comprehension.
Summary & Stage 5 Capstone
Congratulations on finishing Stage 5: Data Structures & Collections! You now command the primary data containers of Python:
- Lists: Dynamic, ordered, mutable sequences.
- Tuples: Fixed, immutable records and hashable keys.
- Dictionaries: Fast $O(1)$ key-value associations.
- Sets: Deduplicated, mathematical collections.
- Comprehensions: Elegant, fast one-liners for creating and transforming collections.
Now that you can store, organize, and transform complex datasets, the next step is packaging your logic into reusable, modular blocks in Stage 6, starting with functions.