Comprehensions: A Shorter Way to Build Collections
The problem...
You want a list of squares for numbers 1 through 10.
The loop version works:
squares = []
for n in range(1, 11):
squares.append(n ** 2)
print(squares)
Output → [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Four lines. One empty list. One loop. One append. It does the job.
But Python has a shorter way.
The idea!
A comprehension builds a collection in a single expression.
Same logic as the loop — but written inline, without the setup.
squares = [n ** 2 for n in range(1, 11)]
print(squares)
Output → [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
One line. Same result.
The anatomy
[expression for item in iterable]
- expression — what you want each element to be
- item — the loop variable
- iterable — what you're looping over
Read it left to right: "give me n ** 2 for each n in range(1, 11)".
Adding a condition
You can filter elements with an if at the end:
[expression for item in iterable if condition]
evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens)
Output → [2, 4, 6, 8, 10]
"Give me n for each n in range, but only if n is even."
What's really happening
A comprehension is not magic — it's a loop and an append, compressed into one line.
Python reads the comprehension, runs the loop internally, and builds the collection.
The result is exactly what the loop version would produce.
Heads up!
- Comprehensions are for building collections — not for side effects like printing
- Keep them readable — if the logic is complex, a regular loop is clearer
- They work with any iterable — lists, ranges, strings, dicts, sets
The mindset shift
Stop thinking: "I need a loop and an empty list."
Start thinking: "If I'm building a collection from another collection — a comprehension probably fits."
What you should understand now
- A comprehension builds a collection in one expression
- Syntax:
[expression for item in iterable] - Add a filter:
[expression for item in iterable if condition] - Same result as a loop — just shorter
- Works with any iterable