Skip to the workspace
Pebellslearn by building
Functional Python  ›  Lesson

Generator Expressions

Generator Expressions 19 minA generator expression creates an iterator that evaluates an expression as its values are consumed.

A generator expression creates an iterator that evaluates an expression as its values are consumed.

Separate creation from consumption, stop early and inspect what remains after a first consumer advances the cursor.

Finding the first expensive order should not require building a list of every expensive order. A generator expression delays its per-item work until a consumer asks. Use that delay deliberately: it enables early stopping, but it also affects when names are read and whether the same source can be consumed again.

A generator supplying values on demand beside a list holding all produced values

Read the tap as a picture of delayed output production, not total memory. The source collection may already exist, and the generator retains references and paused state while a consumer can retain every result it receives.

Total a huge order log

A store's order log has a million rows. Summing the prices doesn't need all of them sitting in memory at once — it only ever needs the running total and whichever price it's looking at right now:

python

The generator avoids the intermediate list. sys.getsizeof is a shallow measurement: it does not include referenced input objects or all retained state, and exact sizes vary with the runtime. Count the entire pipeline's retained objects when assessing memory.

Preparing this topic’s interactive investigation…

Stop at the first order over budget

next(gen, default) requests one yielded value, potentially scanning several source items to find it — useful for "find the first thing that matches" without scanning, building, or even looking at, everything after it:

python

The generator remembers exactly where it paused. The second next() doesn't rescan from the start — it picks up right after 120 and finds 200. A list comprehension would have built [120, 200] in full before you ever asked for the first item.

Creation time and consumption time are different

A generator expression evaluates its leftmost iterable expression when it is created. Its item expression and filters run later, as values are requested. Names used in those later calculations can therefore observe later values.

python

The result is [25], not [15, 25]: the filter reads limit during consumption. Rebinding values to another list after creation would not replace the already chosen source iterator. Mutating the original list is a different operation and can affect what that iterator sees. These are the same binding-versus-object distinctions used in the scope and data-model lessons.

Short-circuit consumers perform only enough work to answer: any stops on the first truthy value, all on the first falsey value, and next on the next yielded value. sum and max need the complete finite stream. In particular, a filter may examine many inputs before next gets one output.

Three new generators over one exhausted iterator do not create three new passes. The later stats exercise uses a reusable list; accepting a stream would require one combined pass or deliberate storage. Try replacing that list with iter(...) and locate the consumer that drains it. Decide whether your function promises a reusable sequence or any iterable before choosing its algorithm.

The reuse trap

A generator is a one-way street. Once it's been walked, it reports nothing else — even a fresh for loop over it finds it empty:

broken — fix it

Run it and notice the total is wrong, not an error. Then get both the highest value and the true total from the same data.

Fix it by keeping a list when you need more than one pass: readings = [12, 45, 8, 90], then max(readings) and sum(readings) both work, because a list can be walked again and again. A generator expression fits a single traversal; multiple consumers can instead share a deliberately materialised result or use freshly constructed pipelines over a source that supports another pass.

Quick practice

What does this print?
nums = [1, 2, 3]
squares = (n * n for n in nums)
print(type(squares).__name__)
What does this print?
nums = [-3, 5, -1, 8]
print(any(n < 0 for n in nums))
What does this print?
g = (x for x in range(3))
first_pass = list(g)
second_pass = list(g)
print(first_pass, second_pass)
What does this print?
prices = [100, 250, 80]
total = sum(p for p in prices if p > 90)
print(total)

🎯 Your turn

Write first_over_budget(orders, budget). Build a generator expression that keeps only the order amounts above budget, then use next(..., None) to return the first one — without ever building a list of all of them. Return None if nothing qualifies.

  • first_over_budget([50, 80, 120, 200], 100) → 120
  • first_over_budget([10, 20], 100) → None

Hint: over = (o for o in orders if o > budget), then return next(over, None).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a single filtered sum to a small stats report built entirely out of generators.

Your task
Write first_over_budget(orders, budget). Build a generator expression that keeps only the amounts above budget, then use next(..., None) to return the first one, without ever building a list of all matches. Example: first_over_budget([50, 80, 120, 200], 100) -> 120 · first_over_budget([10, 20], 100) -> None.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upSum only what's above a threshold

Write total_over(nums, threshold) returning the sum of every number in nums greater than threshold, using a generator expression fed straight into sum() — no list, no parentheses of its own since it's the only argument.

generator-expression
DrillIs anything negative?

Write any_negative(nums) returning True if any number in nums is negative, else False, using any() with a generator expression (so it can stop at the first match).

generator-expression
BuildCount without building a list

Write count_matches(words, prefix) returning how many strings in words start with prefix, using sum(1 for ... if ...) — a common idiom for counting with a generator.

generator-expression
BossStop at the first big square

Write first_square_over(nums, limit) returning the first value of n * n (for n in nums, in order) that is greater than limit, using a generator expression and next(..., None). Return None if none qualify.

generator-expressionnext
CapstoneA stats report built entirely from generators

Given nums as a reusable list, write batch_stats(nums) returning {"total": ..., "count_positive": ..., "first_negative": ...}: the sum of all numbers, how many are positive, and the first negative number (or None if there isn't one). Use a generator expression for each — no list should ever be built.

generator-expressionnext
Project context and further resources
first_over_budget.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
first_over_budget(orders, budget) → intThe first order amount above budget, found lazily, or None if none qualify.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.