Predict the Output - Generator Laziness
Problem
Read the following program and write down exactly what it prints, in order, before running it. Then explain each line of output.
def load(ids):
for i in ids:
print("loading", i)
yield i * 2
ids = [1, 2, 3]
rows = load(ids)
ids.append(4)
print("created")
first = next(rows)
print("first =", first)
total = sum(rows)
print("total =", total)
print("again =", list(rows))
scale = 10
scaled = (n * scale for n in ids)
scale = 100
ids = [0]
print(list(scaled))The questions the interviewer will ask: Does load print anything before "created"? Does the appended 4 get loaded? What is total? What is again? What does the last line print, and why do the scale and ids rebinding have different effects?
Examples
The program prints:
created
loading 1
first = 2
loading 2
loading 3
loading 4
total = 18
again = []
[100, 200, 300, 400]createdcomes first because calling a generator function runs none of its body.total = 18is4 + 6 + 8: the1was consumed bynext, and the appended4is seen because the generator iterates the live list.again = []because a generator is single-use.- The last line uses
scale = 100(looked up late) but the originalidslist (bound early), so it produces four values, not one.
Hints
- Calling a generator function returns a generator object. When does the first line of its body execute?
rowsholds a reference to the list objectidspointed to at call time. What doesids.append(4)do to that object, versusids = [0]?- In a generator expression, the outermost
forclause's iterable is evaluated immediately. Everything else is evaluated per item, when the item is requested.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.