Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
A comprehension is a small loop folded into one line. Every form is shown beside the loop it replaces: lists, the if at the end versus if/else at the front, dicts, sets, two fors, generator expressions, and when to go back to a loop.
What you will learn
- Fold a for loop that appends into a list comprehension, and read one back as a loop
- Tell an if at the end (a filter) from an if/else at the front (a choice of value)
- Write dict and set comprehensions and two-for comprehensions such as flattening a grid
- Use a generator expression inside sum, any and max, and know when a plain loop reads better
Before you start
- Looping Over Real Data in Python
- Python lambda, map, filter, Modules and Packages
AI tools write comprehensions all the time, so you need to read them. A comprehension is a small loop folded into a single line.
Say you need a tray of filled cups and you're explaining it to a friend. You could give steps: take an empty tray, pick up each cup from the shelf, fill it, put it on the tray. Or one sentence: a filled cup, for every cup on the shelf. Same tray. The sentence says what you want first and where it comes from after. The steps are the loop; the sentence is the comprehension.
The fold
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)
squares = [n * n for n in numbers]
print(squares)
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
n * n, the value you were appending, slides to the front. for n in numbers comes behind it and the colon drops off. Square brackets go around both and replace the empty list, and append falls away because the brackets already mean "build a list".
An if at the end is a gate
scores = [85, 42, 91, 67, 78]
passed = []
for s in scores:
if s >= 70:
passed.append(s)
print(passed)
passed = [s for s in scores if s >= 70]
print(passed)
[85, 91, 78]
[85, 91, 78]
The if slides to the end. It decides which items get in, which is why the new list can be shorter.
An if/else at the front is a choice
scores = [85, 42, 91, 67, 78]
labels = []
for s in scores:
if s >= 70:
labels.append("pass")
else:
labels.append("retry")
print(labels)
labels = ["pass" if s >= 70 else "retry" for s in scores]
print(labels)
['pass', 'retry', 'pass', 'retry', 'pass']
['pass', 'retry', 'pass', 'retry', 'pass']
Every score stays; only the label changes, so the whole choice slides to the front. Five scores in, five labels out. This one difference trips up a lot of people, so when you read a comprehension, first check where the if is sitting. At the end, it drops items. At the front with an else, it keeps every item and changes its value.
Dict comprehensions
names = ["maya", "ravi", "zoe"]
lengths = {}
for name in names:
lengths[name] = len(name)
print(lengths)
lengths = {name: len(name) for name in names}
print(lengths)
prices = {"pen": 10, "book": 250, "bag": 900}
cheap = {k: v for k, v in prices.items() if v < 500}
print(cheap)
{'maya': 4, 'ravi': 4, 'zoe': 3}
{'maya': 4, 'ravi': 4, 'zoe': 3}
{'pen': 10, 'book': 250}
key: value goes at the front, inside curly braces; the colon tells you it's a dict. You'll often see it with .items(). Read it in order: for k and v in prices.items(), if v is under 500. The bag at 900 doesn't get through.
Set comprehensions
words = ["tea", "cup", "pot", "kettle", "tea"]
sizes = set()
for w in words:
sizes.add(len(w))
print(sizes)
sizes = {len(w) for w in words}
print(sizes)
{3, 6}
{3, 6}
Curly braces with no colon give a set. Tea, cup and pot all give 3, and a set keeps one of each, so the threes land on the same spot. Reach for this when you want distinct values, and remember a set doesn't promise any order.
Two loops in one line
sizes = ["S", "M"]
colors = ["red", "blue"]
pairs = []
for size in sizes:
for color in colors:
pairs.append((size, color))
print(pairs)
pairs = [(s, c) for s in sizes for c in colors]
print(pairs)
grid = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in grid for n in row]
print(flat)
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
[1, 2, 3, 4, 5, 6]
The two fors stay in the same order as the loop: outer first, then inner. That's the part people misread. The last line flattens a list of lists: for each row in the grid, for each n in that row. Two fors is about the limit; beyond that, a plain loop is kinder to whoever reads it.
Generator expressions
numbers = [1, 2, 3, 4, 5]
total = sum([n * n for n in numbers])
print(total)
total = sum(n * n for n in numbers)
print(total)
print(any(n > 4 for n in numbers))
print(max(len(w) for w in ["tea", "kettle", "cup"]))
lazy = (n * n for n in numbers)
print(type(lazy).__name__)
print(list(lazy))
55
55
True
6
generator
[1, 4, 9, 16, 25]
When you only need one answer, drop the square brackets. It still gives 55, but no list gets built; each value joins the total and is gone. This is a generator expression, and it fits well inside sum, any and max. With round brackets and a name, its type is generator: nothing has been worked out yet, until list asks for the values. Square brackets give you the whole list now; round brackets give you values when they're asked for.
map and filter, side by side
numbers = [1, 2, 3, 4, 5, 6]
by_map = list(map(lambda n: n * 2, numbers))
by_comp = [n * 2 for n in numbers]
print(by_map == by_comp)
by_filter = list(filter(lambda n: n % 2 == 0, numbers))
by_comp = [n for n in numbers if n % 2 == 0]
print(by_filter == by_comp)
print(by_comp)
True
True
[2, 4, 6]
map is the front of the comprehension and filter is the if at the end. You'll see both in AI code, but many Python developers prefer the comprehension, since there's no lambda to read. (More on these two in lambda, map and filter.)
The loop variable stays inside
numbers = [1, 2, 3]
doubled = [n * 2 for n in numbers]
print(doubled)
print(n)
[2, 4, 6]
Traceback (most recent call last):
File "S02L02_1_Comprehensions\comprehension_scope.py", line 4, in <module>
print(n)
^
NameError: name 'n' is not defined
The n in a comprehension belongs to that comprehension. Unlike a for loop, you can't use it after the line ends.
When a loop reads better
orders = [
{"item": "pen", "qty": 3, "paid": True},
{"item": "book", "qty": 0, "paid": True},
{"item": "bag", "qty": 2, "paid": False},
]
squeezed = [o["item"].upper() if o["qty"] > 0 else "NONE"
for o in orders if o["paid"]]
print(squeezed)
result = []
for o in orders:
if not o["paid"]:
continue
if o["qty"] > 0:
result.append(o["item"].upper())
else:
result.append("NONE")
print(result)
print(squeezed == result)
['PEN', 'NONE']
['PEN', 'NONE']
True
The squeezed line has an if/else at the front, a for, and another if at the end. Try reading it out loud. The plain loop gives the same result and is far easier to check. A good rule: one for and one if, use a comprehension. More than that, or anything other than building a collection, use a loop. And if an AI tool hands you a line you can't read, prompt it: "Rewrite this as a plain loop."
Quick recap
| Brackets | You get | Example |
|---|---|---|
[ ] | list | [n * n for n in numbers] |
{k: v} | dict | {name: len(name) for name in names} |
{ } | set | {len(w) for w in words} |
( ) | generator | sum(n * n for n in numbers) |
if at the end | fewer items | [s for s in scores if s >= 70] |
if/else at the front | same count, new values | ["pass" if s >= 70 else "retry" for s in scores] |
Try it yourself
Take the loop that collected the passed students in Looping over real data and write it as a comprehension. You should get ['Maya', 'Zoe'] both ways.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)