Write list, dict, and set comprehensions for concise data transformation
Understand generator expressions and the yield keyword
Know when to use generators vs. lists for memory efficiency
Use built-ins like map(), filter(), and zip()
📊 Comprehension Builder
Click examples to see the loop version, the comprehension version, and the result — side by side.
Loop Version
Comprehension
Result
List Comprehensions
A list comprehension is a concise way to build a list by applying an expression to each item in an iterable, with an optional filter. Syntax: [expression for item in iterable if condition].
Comprehensions are more readable than equivalent for-loops and usually slightly faster because they are optimized by Python's interpreter.
Dict and Set Comprehensions
{k: v for k, v in pairs} — dict comprehension. Build a dict from any iterable of key-value pairs.
{x**2 for x in range(10)} — set comprehension. Like a list comprehension but produces a set (no duplicates, unordered).
Generators
A generator is an object that produces values one at a time instead of building the whole collection in memory. Use () instead of [] for a generator expression, or use yield in a function. Generators are essential when working with large datasets or infinite sequences.
List: builds everything in RAM immediately. Generator: produces values on demand — much lower memory use.
Quick Check
1. What does [x**2 for x in range(5)] produce?
[1, 4, 9, 16, 25]
[0, 1, 4, 9, 16]
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
2. What is the main advantage of a generator over a list?
Generators are always faster at element access
Generators produce values one at a time, using far less memory
Generators can hold more items than lists
Generators support more methods than lists
3. Which syntax creates a generator expression (not a list)?
[x for x in data]
(x for x in data)
{x for x in data}
gen[x for x in data]
4. What does the yield keyword do in a generator function?
It returns a value and terminates the function
It pauses the function, produces the value, and resumes on next iteration