Q1What does this code print?nums = [1, 2, 3, 4]
result = [n * 10 for n in nums]
print(result)
List Comprehensions and Dict / Set / Generator Expressions — Build Collections in One Line
Build Python collections in a single line with comprehensions and generator expressions, all runnable in your browser.
In the previous article on all() / any(), you saw how to judge a whole collection at once. This time, you'll go one step further and look at the powerful syntax for building the collection itself in a single line — comprehensions.
We'll start with list comprehensions, add filtering with if, see the dict and set variants, and finish with the memory-saving generator expression.
List Comprehension Basics — Squeeze a for Loop into One Line
Python has a one-line syntax for building lists: [expression for variable in iterable]. This is called a list comprehension.
It's a shortcut for the for loop pattern of starting with an empty list and calling append() repeatedly, and it shines when you want to apply the same transformation to every element and produce a new list.
[expression for variable in iterable] produces a new list with each element transformed by the expression. It's the one-line version of writing a for loop with append.
# Using a for loop
result = []
for price in [100, 250, 480]:
result.append(int(price * 1.1))
print(result) # [110, 275, 528]
# Same thing as a list comprehension
prices = [100, 250, 480]
tax_included = [int(p * 1.1) for p in prices]
print(tax_included) # [110, 275, 528]
# Collecting string lengths in one line too
names = ["Alice", "Bob", "Charlotte"]
lengths = [len(n) for n in names]
print(lengths) # [5, 3, 9]
Filter with if — Conditional Comprehensions
Add if condition after for and only elements that satisfy the condition end up in the new list. The form is [expression for variable in iterable if condition].
Writing the transformation and the filter on the same line is what makes list comprehensions concise — pulling out "only the elements that match" becomes one short, readable line.
if p >= 200 one at a time. True elements (kept) end up in the new list; False elements (skipped) are dropped.# Pull out only items >= 200
prices = [80, 250, 120, 480, 95]
premium = [p for p in prices if p >= 200]
print(premium) # [250, 480]
# Filter and transform at the same time
discounted = [int(p * 0.9) for p in prices if p >= 200]
print(discounted) # [225, 432] ← 10% off, only items >= 200
# Filter and transform on strings
names = ["Alice", "Bob", "Charlotte", "Ed"]
long_names = [n.upper() for n in names if len(n) >= 5]
print(long_names) # ['ALICE', 'CHARLOTTE']
Dict Comprehensions and Set Comprehensions
Swap the square brackets [ ] of a list comprehension for curly braces { } and you get a set comprehension.
Go a step further with {key: value for ...} and the colon turns it into a dict comprehension. The for ... in ... syntax is identical — only the shape of the output collection changes, and that flexibility is what makes comprehensions so handy.
{key: value for ...} builds a dict of pairs. From a list of (name, price) tuples you can construct a "name → price" lookup in one line.
# Dict comprehension: build a name → price lookup
pairs = [("apple", 120), ("orange", 80), ("banana", 60)]
price_lookup = {name: price for name, price in pairs}
print(price_lookup)
# {'apple': 120, 'orange': 80, 'banana': 60}
# Rebuild a dict with tax-included prices
tax_included = {name: int(price * 1.1) for name, price in pairs}
print(tax_included)
# {'apple': 132, 'orange': 88, 'banana': 66}
# Set comprehension: pull out unique tags (no duplicates)
tags = ["sale", "new", "sale", "limited", "new"]
unique = {t for t in tags}
print(unique) # {'sale', 'new', 'limited'} (order is implementation-dependent)
Pair zip() with dict comprehensions
When you have two parallel lists like names and prices and want a dict, {n: p for n, p in zip(names, prices)} is a clean fit. zip() walks the lists in lockstep so you can build the keys and values at the same time.
Generator Expressions — Switch Square Brackets for Parens
Swap the square brackets [ ] of a list comprehension for parentheses ( ) and you have a generator expression. Unlike a list, it doesn't materialize all elements in memory — it computes only what you need, when you need it (lazy evaluation).
You can pass it directly to sum() / max() / min() / any() and so on, which keeps memory use down when aggregating large data. The full deep dive is in the generator function article later on.
| Syntax | Result type | Characteristic |
|---|---|---|
| [x for x in items] | list | Holds all items in memory |
| {x for x in items} | set | No duplicates, all in memory |
| {k: v for k, v in items} | dict | Key: value pairs, all in memory |
| (x for x in items) | generator | Only the current item, lazy |
# Parentheses make a generator expression
prices = [100, 250, 480, 1200]
gen = (int(p * 1.1) for p in prices)
print(type(gen)) # <class 'generator'>
# Pass it straight to sum() (the outer parens can be omitted)
total_tax = sum(int(p * 1.1) for p in prices)
print(total_tax) # 2233
# Same trick with max() / min()
max_tax = max(int(p * 1.1) for p in prices)
print(max_tax) # 1320
Pick by use case: "all at once?" or "one at a time?"
If you want the whole thing as a list in your hand, use [ ] (list comprehension). If you're just passing it to sum() / max() to aggregate, ( ) (generator expression) is the memory-friendlier choice. At a million-element scale the difference is dramatic — the generator expression uses just a few hundred bytes.
Knowledge Check
Answer each question one by one.
Q2What does this code print?nums = [1, 2, 3, 4, 5]
result = [n for n in nums if n % 2 == 0]
print(result)
Q3Which of these creates a dict?