List Comprehensions and Generator Expressions in Python: A Complete Guide (2026)
List Comprehensions and Generator Expressions are two ways to write the exact same idea: build a new sequence by taking each item from an existing one, transforming it, and optionally filtering it, all without a separate loop. Module 8 closed by mentioning the loops that built its example tables. This is how those loops get rewritten as one line each, and the real difference between the two forms once that line runs.
Quick Answer: List Comprehensions and Generator Expressions
A list comprehension, written with square brackets, builds a complete new list in memory right away: [x for x in items if condition]. A generator expression, written with parentheses instead, produces the same values one at a time, on demand, and never stores the full sequence. Use a list comprehension by default. Switch to a generator once the data is large, unbounded, or only needs to be read through a single time.
One Loop, One Line
A list of prices needs just the expensive ones, anything over 10, pulled into their own list. The instinct most people learn first is a loop.
prices = [12.99, 2.50, 6.00, 45.00, 3.75, 89.99] expensive = [] for p in prices: if p > 10: expensive.append(p)
Four lines collapse into one with a list comprehension:
expensive = [p for p in prices if p > 10] # [12.99, 45.0, 89.99]
Same result, same order, same values. A comprehension is not a shortcut trick layered on top of the loop. It is Python's own built-in way of expressing this exact pattern: build a new sequence by taking each item from an iterable and optionally filtering it first.
List Comprehension Syntax
The shape is always the same: an expression, a for clause, and an optional if clause, all inside square brackets.
[expression for item in iterable if condition]
The expression can transform the value, not just pass it through unchanged. A 10 percent discount on every expensive item:
discounted = [round(p * 0.9, 2) for p in prices if p > 10] print(discounted) # [11.69, 40.5, 80.99]
Generator Expressions: The Lazy Twin
The exact same filtering and transforming logic works as a generator expression. Only the brackets change.
expensive = (p for p in prices if p > 10) print(expensive) # <generator object <genexpr> at 0x7f0917396330>
Nothing has actually been computed yet. A generator does not hold a result, it holds a recipe: instructions for producing values one at a time, whenever something asks for the next one.
next(expensive) # 12.99 next(expensive) # 45.0
Memory vs. Speed: The Real Tradeoff
A list comprehension builds the entire list in memory immediately. A generator produces one value at a time and forgets it once it moves on. For ten thousand integers, that difference is dramatic:
from sys import getsizeof big_list = [n for n in range(10000)] big_gen = (n for n in range(10000)) print(getsizeof(big_list)) # 85176 print(getsizeof(big_gen)) # 192
The generator stays at roughly 192 bytes no matter how large the range gets, since it never stores more than the single value it is currently producing. That makes generators the right choice for huge or open ended sequences, reading a massive file line by line, for example, where building the whole thing in memory first is not an option.
For smaller, everyday sizes, a list comprehension is usually both simpler and faster. It computes everything in one efficient pass, while a generator pays a small overhead each time it is asked for its next value. "Always use a generator" is an oversimplification. Reach for one once memory, not speed, becomes the actual concern.
The Exhaustion Trap
A generator can only be walked through once. Every value it yields is gone the moment it is produced.
expensive = (p for p in prices if p > 10) next(expensive) # 12.99 next(expensive) # 45.0 list(expensive) # [89.99] only what was left list(expensive) # [] nothing left, it already ran once
A list comprehension has no such trap. It is a normal list, and can be looped over, sliced, or read from as many times as needed, since it already holds every value it will ever hold.
Bonus: Dict and Set Comprehensions
The same for-and-if pattern builds dictionaries and sets too, using curly braces instead of square brackets or parentheses.
price_lookup = {"mug": 12.99, "pen": 2.50, "notebook": 6.00}
on_sale = {item: round(price * 0.9, 2) for item, price in price_lookup.items()}
print(on_sale)
# {'mug': 11.69, 'pen': 2.25, 'notebook': 5.4}
A dict comprehension needs a key and a value, separated by a colon, ahead of the for clause. A set comprehension looks like a list comprehension with curly braces instead, and automatically drops duplicates:
unique_price_points = {round(p) for p in prices}
print(unique_price_points)
# {2, 4, 6, 45, 13, 90} order is not guaranteed, sets are unordered
There is no tuple comprehension. Wrapping the same syntax in parentheses builds a generator instead, as seen above. Getting an actual tuple out of one takes an explicit call: tuple(p for p in prices if p > 10).
What Changed in Python 3.12
Comprehensions got faster without any code needing to change. Starting with Python 3.12, released in October 2023, list, dict, and set comprehensions are inlined directly into the surrounding code instead of quietly compiling to a hidden, single-use function that got called on every execution. The practical result is up to twice the speed on the comprehension itself, with no syntax difference at all.
Material written before late 2023 may still describe a comprehension as secretly creating its own function under the hood. That description used to be accurate. Since Python 3.12 it no longer is, though the comprehension's variables are still isolated from the surrounding code exactly as before, the isolation just works differently under the surface.
Mistakes That Give Away a Beginner
- Reusing a generator a second time and getting nothing back, forgetting it already ran once.
- Wrapping a comprehension in parentheses expecting a tuple, and getting a generator object instead. There is no tuple comprehension.
- Choosing a generator by default for small, reused data, where a plain list comprehension would be simpler and just as fast.
- Nesting comprehensions two or three levels deep until nobody, including whoever wrote it, can read it at a glance.
- Forgetting a dict comprehension needs a key and a value separated by a colon, not a single expression like a list comprehension.
Practice: Fix These Three Yourself
Rewrite the loop
Take a for loop that builds a list of every word longer than 4 characters from a sentence, and rewrite it as a single list comprehension.
Prove the exhaustion
Create a generator expression, call next() on it twice, then call list() on it twice, and confirm the second list() call returns an empty list.
Three kinds of brackets
Starting from the same prices list, write a list comprehension, a set comprehension, and a dict comprehension that each use it differently.
Frequently Asked Questions
What is a list comprehension in Python?
A concise way to build a new list by applying an expression to each item in an iterable, optionally filtering with an if clause, all in a single line: [expression for item in iterable if condition].
What's the difference between a list comprehension and a generator expression?
A list comprehension builds the entire list in memory immediately. A generator expression, written with parentheses instead of square brackets, produces one value at a time on demand and never stores the whole sequence.
Why can a generator only be used once?
A generator does not hold a stored sequence, it holds a recipe plus a position in that recipe. Once every value has been produced, there is nothing left to give out, and it will not restart on its own.
Are list comprehensions faster than for loops?
Usually yes, and since Python 3.12 they are faster still, since comprehensions are now inlined instead of compiling to a hidden function call. For very small pieces of code the difference is negligible either way.
How do you write a dictionary comprehension?
Use curly braces with a key and a value separated by a colon, followed by a for clause: {key: value for item in iterable}.
What changed with comprehensions in Python 3.12?
List, dict, and set comprehensions are now inlined into the surrounding code instead of compiling to a separate hidden function, making them up to twice as fast with no change to the syntax.
Conclusion: Two Postures, One Idea
A list comprehension and a generator expression describe the same idea in two different postures: one builds everything right away, the other holds back and produces values only when asked. Reach for a comprehension by default, and switch to a generator once the data is large enough, or open ended enough, that holding all of it in memory at once stops making sense.
Practice the three exercises above, then move to the next article in this cluster, which returns to pandas to handle missing data directly: finding it, filling it, and deciding when to drop it instead.
Next Up: Handling Missing Data in Pandas
NaN, fillna, and dropna: finding gaps in real data and deciding what to do with them.
▶ Read the Missing Data GuideKhalid Hussain
Founder of Review Publically. MSc holder and Google Advanced Data Analytics certified. Teaches Python and SQL data analysis with a focus on current, correct, production-ready code rather than outdated conventions.
Related Modules