Comprehensions — list, dict, set, generator
One-line loops that build collections. Faster and more Pythonic than for+append.
script.py
v3.1
Python output
click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
The output will appear here.
🧠 How it works
[expr for x in iter if cond] — list comprehension. The if is a FILTER (skips items where cond is False). [a if cond else b for x in iter] — if/else EXPRESSION (maps each item to a or b). Different syntax! {k: v for k, v in iter} — dict comprehension. {x for x in iter} — set comprehension (deduplicates). (expr for x in iter) — generator expression. Lazy — produces values on demand. Memory-efficient for big data. Comprehensions are FASTER than for+append because the loop runs in C, not Python. Don't overdo it — if your comprehension is more than 1 line, use a regular for loop for readability.
✏️ Try these changes
-
Change [x*x for x in range(5)] to [x*x for x in range(5) if x % 2 == 0]→ only squares of evens: [0, 4, 16] -
Change the if/else to 'positive' if x > 0 else 'zero' if x == 0 else 'negative'→ nested ternary (hard to read — use a function) -
Change square_dict to {x: x*x for x in range(10) if x % 2 == 0}→ only even keys -
Change the generator to a list: list(x*x for x in range(5))→ same as list comprehension