Skip to contentSkip to navigation

Module 13 · Lesson 02

Generator Expressions and Lazy Evaluation

Build iterators in one line with generator expressions, feed them straight into sum, any, all, max and next, and chain them into lazy pipelines that handle big data in small memory.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • List or generator: spot the brackets
  • Watch laziness step by step
  • Totals with sum, any and all
  • Chain generators into a pipeline

Round brackets, lazy results

A generator expression looks like a list comprehension, but works out each item only when asked.

  • The shape

    (n * 2 for n in nums): a comprehension with round brackets.

  • Lazy

    Nothing is calculated until a loop, list() or sum() asks for the next item.

  • Feed it in

    sum(n * n for n in nums) needs no extra brackets when it is the only argument.

  • Stop early

    any(), all() and next() stop as soon as they know the answer.

Lazy work everywhere

Big data is often handled one item at a time, never all at once.

  • Huge logsCount the error lines of a log file bigger than the computer's memory.
  • CheckoutsAdd up a basket with sum(price * qty for ...) and no temporary list.
  • High scoresmax(p.score for p in players) finds the best score in one pass.
  • Health checksall(s.ok for s in servers) stops at the first server that is down.

Adding up without a list

This line doubles the prices over 5 and adds them up. Tap each part to see its job.

Part 1 of 7

Tap any part of the code below, or press Next.1 of 7 explored

result:sum() gives back a single number, not a list.

Work it out only when asked

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6List or generator

Same shape, different brackets. Printing the generator shows no numbers yet.

Your turn: Change the brackets on as_list to round ones. What does it print now?

Python
nums = [1, 2, 3]
as_list = [n * 10 for n in nums]
as_gen = (n * 10 for n in nums)
print(as_list)
print(as_gen)
print(list(as_gen))
Output
Press Run to see what it prints.

Watch a generator get used up

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. nums = [4, 9, 2]
  2. gen = (n * 3 for n in nums)
  3. a = next(gen)
  4. rest = sum(gen)
  5. print(a, rest)
  6. print(sum(gen))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.What prints?

gen = (print("hi") for _ in range(2))
print("start")

0 of 6 answered

Common generator expression misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Same shape, different brackets

You already know list comprehensions:

Try it 1: edit me, then Run
squares = [n * n for n in range(5)]
print(squares)          # [0, 1, 4, 9, 16]
Output
Press Run to see what it prints.

Swap the square brackets for round ones and you get a generator expression:

Try it 2: edit me, then Run
squares = (n * n for n in range(5))
print(squares)          # <generator object <genexpr> at 0x...>
print(list(squares))    # [0, 1, 4, 9, 16]
Output
Press Run to see what it prints.

Printing it does not show any numbers, because none have been calculated yet. A generator expression creates a generator, which is an iterator, like the ones in the previous lesson. It works out each item only when next() is called on it, by a for loop, list(), sum() or anything else that consumes items.

Lazy evaluation

"Lazy" means the work happens as late as possible. You can see it with a function that reports when it runs:

Try it 3: edit me, then Run
def double(n):
    print("doubling", n)
    return n * 2

gen = (double(n) for n in [1, 2, 3])
print("nothing done yet")
print(next(gen))
Output
Press Run to see what it prints.

This prints nothing done yet first, then doubling 1 and 2. The second and third items have still not been calculated. A list comprehension would have printed all three "doubling" lines immediately.

Laziness gives two big advantages:

  • Memory. A list of a million numbers holds a million objects at once. A generator holds one item and its position, so its size stays small however many items it will eventually produce.
  • Stopping early. If the consumer stops after a few items, the rest are never computed at all.

Feeding functions directly

When a generator expression is the only argument to a function, you can drop its own brackets:

Try it 4: edit me, then Run
prices = [4.5, 12.0, 3.25, 20.0]
print(sum(p * 1.2 for p in prices))       # total with tax
print(max(len(w) for w in ["a", "abc"]))  # 3
print(", ".join(w.upper() for w in ["x", "y"]))   # X, Y
Output
Press Run to see what it prints.

This reads naturally ("the sum of p times 1.2 for each p in prices") and never builds a temporary list. If the function takes other arguments, the generator needs its brackets back: sorted((n % 3 for n in nums), reverse=True).

any, all and next stop early

any() returns True as soon as it finds one true item; all() returns False as soon as it finds one false item. With a generator expression they stop pulling items the moment they know the answer:

Try it 5: edit me, then Run
temps = [21, 23, 39, 22, 20]
print(any(t > 35 for t in temps))    # True after checking only three
print(all(t > 0 for t in temps))     # True
Output
Press Run to see what it prints.

next() with a generator expression finds the first match, and its default covers "no match":

Try it 6: edit me, then Run
first_hot = next((t for t in temps if t > 35), None)
print(first_hot)                      # 39
Output
Press Run to see what it prints.

Here the brackets are needed, because next has a second argument.

Pipelines

Because each generator expression can read from another, you can build a pipeline: a series of small steps, each lazy, that items flow through one at a time.

Try it 7: edit me, then Run
lines = ["  ok 12", "", "ERROR 7", "ok 3  ", "ERROR 40"]
cleaned = (line.strip() for line in lines)
non_empty = (line for line in cleaned if line)
errors = (line for line in non_empty if line.startswith("ERROR"))
codes = (int(line.split()[1]) for line in errors)
print(sum(codes))                     # 47
Output
Press Run to see what it prints.

No step runs until sum() starts asking for items. Then the first line travels through every stage, then the second, and so on. Only one line is in flight at a time, so the same code works on a five-line list or a five-gigabyte file opened with open(), since file objects are lazy iterators of lines too.

Generators are one-shot

A generator expression is an iterator, so it can be consumed only once. A second sum() over the same generator gets nothing and returns 0. Also, because it does not hold its items, it has no len() and cannot be indexed: gen[0] and len(gen) both raise TypeError.

Which one to use

Use a list comprehension when you need the result more than once, need its length, want to index or slice it, or want to print it to check. Use a generator expression when the result is consumed once, straight away, especially by sum, any, all, min, max, join or a for loop, or when the input is large or endless. For small data both are fine, and readability matters more than the tiny difference in speed.

Sets and dictionaries have their own comprehensions, {...} with braces, and those are not lazy; there is no tuple comprehension. The round brackets always mean a generator.

Syntax

The general shape of the statements in this lesson.

syntax.py
gen = (expr for item in iterable)            # generator expression
gen = (expr for item in iterable if test)    # with a filter
sum(x * 2 for x in nums)                     # sole argument: no extra brackets
sorted((x % 3 for x in nums), reverse=True)  # other arguments: brackets needed
any(x < 0 for x in nums)                     # stops at the first True
all(x > 0 for x in nums)                     # stops at the first False
next((x for x in nums if x > 10), None)      # first match or None
", ".join(str(x) for x in nums)              # build text lazily
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Totals from an order without a temporary list

Beginner

An order is a list of (item, price, quantity) tuples. Print the number of units, the order total and the most expensive line total, using a generator expression each time.

Python
order = [("pen", 1.50, 4), ("notebook", 3.25, 2), ("stapler", 7.80, 1)]

units = sum(qty for _, _, qty in order)
total = sum(price * qty for _, price, qty in order)
biggest = max(price * qty for _, price, qty in order)

print("Units:", units)
print("Total:", round(total, 2))
print("Largest line:", biggest)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Each generator expression unpacks the tuple and produces one number at a time for sum or max. The underscore is a conventional name for a value we do not need. No list of line totals is ever built.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using a generator twice

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
evens = (n for n in range(10) if n % 2 == 0)
print(sum(evens))
print(sum(evens))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 20 and then 0

Write this instead

evens = [n for n in range(10) if n % 2 == 0]
print(sum(evens))
print(sum(evens))

Why it happens

A generator is one-shot. The first sum used every item, so the second finds none and returns 0.

In the real world

Where this shows up in software people use every day.

  1. Summarising a request log as a stream

    Web operations

    A site's access log grows by millions of lines a day. The on-call engineer wants the number of slow requests and their average time, without loading the log into memory. Here the log is a short string, but the pipeline would read a real file line by line in exactly the same way.

    Why Python fits

    The first three stages are lazy generator expressions, so each log line is cleaned, split and converted only when the next stage asks for it. The last stage is a list on purpose, because the slow times are used three times. With a real file, log.splitlines() would simply become the open file object.

    Python
    log = """GET /home 200 120ms
    GET /cart 200 950ms
    POST /pay 500 1300ms
    # comment line
    GET /home 200 80ms
    GET /search 200 1100ms"""
    
    lines = (line.strip() for line in log.splitlines())
    requests = (line.split() for line in lines if line and not line.startswith("#"))
    times = (int(parts[3].removesuffix("ms")) for parts in requests)
    slow = [t for t in times if t >= 900]
    
    print("Slow requests:", len(slow))
    print("Average slow time:", sum(slow) // len(slow), "ms")
    print("Any over a second?", any(t > 1000 for t in slow))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Is a generator expression faster than a list comprehension?

Not always. For small data a list comprehension can be slightly faster. The big wins of a generator are memory and stopping early, which matter for large or endless inputs.

Can a generator expression read a file?

Yes, and it is one of the best uses. sum(1 for line in open(path) if 'ERROR' in line) counts error lines while holding only one line in memory. In real code put the open in a with block.

Why does sum need no extra brackets but sorted with reverse does?

Python allows the brackets of a generator expression to be dropped only when it is the sole argument. With a second argument the call would be ambiguous, so the generator keeps its own brackets.

What is the difference between a generator expression and a generator function?

Both create generators. An expression fits one simple transform or filter on one line; a generator function, written with yield, can hold loops, conditions and state across many lines. Generator functions come in the next lesson.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.