Python List Comprehension Exercises: Map, Filter, and Build
A comprehension is a compact way to build a collection. The useful question is not “Can I shorten this?” but “Does the transformation stay obvious?”
Map every value
The expression before for is evaluated for every item. The result is a new list. Keep the expression small enough that the reader can see the input and the output at a glance.
nums = [1, 2, 3]
doubled = [n * 2 for n in nums]
print(doubled)Transform each item
Filter first, then transform
An if clause at the end keeps only values that pass the test. Put the condition after the for clause. If the condition needs multiple branches, use a normal loop.
nums = [1, 2, 3, 4]
even = [n for n in nums if n % 2 == 0]
print(even)Keep the even values
Build a dictionary
A dictionary comprehension uses key: value before for. Iterate over items() when you need both the original key and value. The result is a new dictionary, not a modified original.
prices = {"latte": 4.5, "tea": 3.0}
expensive = {name: price for name, price in prices.items() if price >= 4}
print(expensive)Filter a dictionary
Nested loops in one expression
A nested comprehension reads left to right like nested for loops. The first for is the outer loop. If the order is hard to explain, write the loops normally first and compare.
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)A small cartesian product
Prefer readability over cleverness
A comprehension should replace a loop, not hide one. If you need comments inside the expression, or a reader has to scan it twice, use a named function or a normal loop. Shorter is not automatically clearer.
names = ["latte", "tea"]
labels = [name.upper() for name in names if len(name) > 3]
print(labels)A short, readable filter
Your practice checklist
- Write the equivalent for loop first when unsure.
- Put the if filter after the for clause.
- Use a dictionary comprehension for key: value output.
- Keep the expression short enough to read in one pass.
Common questions
Are comprehensions faster than loops?
They can be faster for simple transformations, but readability matters more for beginners. Measure only when performance is a real problem.
Can I use a comprehension for side effects?
You can, but it is unclear. Use a normal for loop when the goal is printing, saving, or changing external state.
What is the difference between a list and a generator expression?
A list comprehension builds the whole list immediately. A generator expression produces values lazily, which can save memory for large inputs.
Practice comprehensions
12 questions on mapping, filtering, dictionary comprehensions, and nested loops.
Keep reading: