Problem solving · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Predict the Output - Generator Laziness

mediumcode-reading

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]
  • created comes first because calling a generator function runs none of its body.
  • total = 18 is 4 + 6 + 8: the 1 was consumed by next, and the appended 4 is 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 original ids list (bound early), so it produces four values, not one.

Hints

  1. Calling a generator function returns a generator object. When does the first line of its body execute?
  2. rows holds a reference to the list object ids pointed to at call time. What does ids.append(4) do to that object, versus ids = [0]?
  3. In a generator expression, the outermost for clause's iterable is evaluated immediately. Everything else is evaluated per item, when the item is requested.

Last reviewed 8 September 2026