A comprehension builds a collection from an iterable in a single, readable expression. It's one of Python's signature idioms — replacing a three-line "create empty list, loop, append" pattern with one clear line, and it's often faster too.
List comprehensions
The shape is [expression for item in iterable]. Compare the loop and the comprehension:
# The long waysquares = []for n in range(6):squares.append(n * n)# The comprehension — same result, one linesquares = [n * n for n in range(6)] # [0, 1, 4, 9, 16, 25]
Filtering & transforming
Add an if to keep only some items, and put any expression on the left to transform them:
evens = [n for n in range(10) if n % 2 == 0] # [0,2,4,6,8]names = ["ana", "ravi"]caps = [name.upper() for name in names] # ['ANA', 'RAVI']# Conditional expression on the left (map every item)labels = ["pass" if s >= 40 else "fail" for s in scores]
Dict & set comprehensions
The same idea builds dicts and sets — just change the brackets:
# dict comprehension {key: value for ...}lengths = {w: len(w) for w in ["hi", "there"]} # {'hi': 2, 'there': 5}# set comprehension {expr for ...}first_letters = {name[0] for name in names} # unique first letters# generator expression (lazy) — parentheses instead of bracketstotal = sum(n * n for n in range(1000)) # no list built
Key takeaways
- 01A comprehension builds a collection in one expression: [expr for x in iterable].
- 02Add if to filter; put an expression (or ternary) on the left to transform.
- 03The same syntax builds dicts {k: v for …} and sets {expr for …}.
- 04(expr for …) is a lazy generator expression — memory-efficient for large data.
- 05Keep them simple — fall back to a loop when the logic gets complex.
