Learn by reading through in order

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 linecomprehensions.

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.

How a list comprehension flows
items =[10, 20, 30][x * 2for x in items][20, 40, 60]apply expression to each elementnew 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]

Build a new list of product prices with 10% tax added, using a list comprehension.

① Declare prices = [100, 250, 480, 1200].

② Use the list comprehension [int(p * 1.1) for p in prices] to build the tax-included list and assign it to tax_included.

③ Print the result with print(tax_included).

(When the answer is correct, the explanation will appear.)

Python Editor

Run code to see output

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.

How a conditional comprehension judges each element
inside the forprices =[80, 250, 120, 480][p for p in pricesif p >= 200]Result[250, 480]p = 8080 >= 200False→ skipp = 250250 >= 200True→ keepp = 120120 >= 200False→ skipp = 480480 >= 200True→ keepapplycomplete
Each element is taken out in order and judged with 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']

From inventory data, pull out product names with stock 1 or more.

① Declare stocks = [("apple", 12), ("banana", 0), ("orange", 5), ("grape", 0), ("kiwi", 3)].

② Use [name for name, count in stocks if count > 0] to build the list of in-stock product names and assign it to available (tuple unpacking lets you bind name and count at the same time).

③ Print the result with print(available).

Python Editor

Run code to see output

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.

How a dict comprehension flows
pairs =[("apple", 120), ("orange", 80)]{name: pricefor name, pricein pairs}{"apple": 120, "orange": 80}unpacknew dict

{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.

From a list of (name, price) tuples, build a product → tax-included price dict in one line.

① Declare pairs = [("apple", 120), ("orange", 80), ("banana", 60), ("kiwi", 200)].

② Use the dict comprehension {name: int(price * 1.1) for name, price in pairs} to build the tax-included lookup and assign it to tax_lookup.

③ Print the result with print(tax_lookup).

Python Editor

Run code to see output

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.

SyntaxResult typeCharacteristic
[x for x in items]listHolds all items in memory
{x for x in items}setNo duplicates, all in memory
{k: v for k, v in items}dictKey: value pairs, all in memory
(x for x in items)generatorOnly 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.

For a list of product prices, compute the total tax-included price by combining a generator expression with sum().

① Declare prices = [100, 250, 480, 1200].

② Compute the tax-included total with sum(int(p * 1.1) for p in prices) and assign it to total (you can drop the generator expression directly inside sum()'s parens).

③ Print the result with print(total).

Python Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1What does this code print?
nums = [1, 2, 3, 4]
result = [n * 10 for n in nums]
print(result)

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?