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()orsum()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()andnext()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 scores
max(p.score for p in players)finds the best score in one pass. - Health checks
all(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
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?
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))
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.
- nums = [4, 9, 2]
- gen = (n * 3 for n in nums)
- a = next(gen)
- rest = sum(gen)
- print(a, rest)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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
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
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.
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)Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
evens = (n for n in range(10) if n % 2 == 0) print(sum(evens)) print(sum(evens))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Web operations
Summarising a request log as a stream
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.Pythonlog = """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))OutputPress 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?
Can a generator expression read a file?
Why does sum need no extra brackets but sorted with reverse does?
What is the difference between a generator expression and a generator function?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.