download

Why did a lazy iterator fail or read mutated data later?

Python~10 minReviewed 3 Dec 2026Free · No sign-in

Question

This code builds two lazy generator expressions: high over a list and rows over a stream opened inside with.

  1. Predict what print(list(high)) outputs after nums is mutated, nums is rebound, and limit changes.
  2. Predict what happens on print(list(rows)) after load_lines(buf) returns.
  3. Fix both cases so high snapshots [2, 3] right away and load_lines streams lines safely while keeping the stream open until finished.
"CODE · PYTHON"
import io

nums = [1, 2, 3]
limit = 1
high = (x for x in nums if x > limit)
nums.append(4)
nums = [99]
limit = 2
print(list(high))


def load_lines(stream):
    with stream as f:
        return (line.strip() for line in f if line.strip())


buf = io.StringIO("alice\n\nbob\n")
rows = load_lines(buf)
print(list(rows))
Show hints (3)
  1. "WHAT RUNS IMMEDIATELY"

    In (x for x in nums if x > limit), Python evaluates the outermost iterable nums at creation time. The if x > limit check waits until next().

  2. "MUTATION VS REBINDING"

    nums.append(4) changes the original list in place, while nums = [99] points the name nums at a different list. Which one does high see?

  3. "FILE CLOSES EARLY"

    load_lines returns a generator without reading a single line, so with stream as f: closes f before the caller iterates. Use yield inside with instead.

Show checked explanation

list(high) prints [3, 4], and list(rows) raises ValueError: I/O operation on closed file. A generator expression binds its leftmost iterable (nums) immediately, so nums.append(4) is seen while nums = [99] is not, and limit = 2 runs lazily on next(). Snapshot with a list comprehension for high, and use yield inside with in load_lines.

"SOLUTION · PYTHON"
import io


def load_lines(stream):
    with stream as f:
        for line in f:
            text = line.strip()
            if text:
                yield text


nums = [1, 2, 3]
limit = 1
high = [x for x in nums if x > limit]
nums.append(4)
nums = [99]
limit = 2
print(high)
buf = io.StringIO("alice\n\nbob\n")
print(list(load_lines(buf)), buf.closed)
"OUTPUT"
[2, 3]
['alice', 'bob'] True

Code run on CPython 3.12.10 against the starter mutations, closed-stream ValueError, fixed solution, and filter/map cases. Checked by an editor other than the author.

Walkthrough

Lazy iterators defer reading elements until a consumer calls next(). That creates two traps: mutating the source before iteration, or closing a resource before iteration starts.

Action after creating iteratorEvaluated when?Effect on starter
nums.append(4)Read at next()Original list becomes [1, 2, 3, 4]; high sees 4
nums = [99]Outer nums bound at creationhigh ignores [99] and keeps the original list
limit = 2if x > limit runs at next()Filters [1, 2, 3, 4] with x > 2, yielding [3, 4]
return (... for line in f)Stream read at next()with closes f on return; list(rows) raises ValueError

Why high prints [3, 4]. Python evaluates the leftmost for iterable (nums) immediately when building a generator expression. That locks high onto the original list object, so rebinding nums = [99] has no effect. Because high has not pulled elements yet, mutating that list with nums.append(4) changes what it reads, and changing limit = 2 changes the lazy if check.

Built-ins filter and map are lazy too. They hold a reference to the source list and wait until iteration:

"PYTHON"
scores = [10, 25, 40]
passed = filter(lambda s: s >= 20, scores)
scores.append(50)
print(list(passed))  # [25, 40, 50]

Why load_lines crashes. Returning a generator expression from inside with stream as f: exits the with block right away and closes f. When the caller later runs list(rows), reading from f raises ValueError: I/O operation on closed file.

Using a list comprehension [...] snapshots high immediately. Turning load_lines into a generator function with yield keeps with stream as f: active while the caller pulls lines, then closes buf once iteration ends (buf.closed becomes True). This differs from reusing an exhausted generator: here the iterator has not even started yet.

Common mistakes

  • Returning a generator expression, map, or filter from inside with open(...) as f:. Exiting with closes the file before the caller pulls the first item.
  • Assuming a generator expression snapshots its source list at creation time. It only stores an iterator over the list, so later append, pop, or clear calls alter the output.
  • Assuming the outermost iterable is lazy too. Rebinding nums = [99] does not redirect high, because Python evaluated nums immediately when creating the generator expression.
  • Materializing a huge multi-gigabyte file with list(f) inside with when you wanted streaming. Use yield inside with or let the caller own the with open(...) block.

Follow-up questions

  • "What happens if the caller breaks out of load_lines after reading one line?" The with block stays paused at yield until the generator closes. CPython closes it on garbage collection by throwing GeneratorExit so __exit__ runs, but PyPy or reference cycles can delay that. Use with contextlib.closing(load_lines(buf)) as rows: or let the caller open the file with with for immediate closing.
  • "What if a generator expression has two for clauses?" Only the leftmost for iterable runs at creation time. Every inner for iterable, if filter, and output expression runs lazily on next(). In (x + y for x in a for y in b), rebinding a later has no effect, while rebinding b before iteration still changes the pairs produced.
  • "What happens if you mutate a dict or set while iterating lazily over it?" Unlike appending to a list, adding or removing keys in a dict or set during iteration raises RuntimeError because the container size changed mid-scan. Snapshot keys with list(mapping) before mutating.

What a strong answer covers

Separates early binding of the leftmost iterable from lazy execution of the filter and body. Predicts [3, 4] and the closed-file ValueError, fixes each with a snapshot list or yield inside with, and knows how early break affects file closing.

Open in interactive practice deck →

Original OfferVibe question. Python Generator Expressions · Python Built-in filter · Python io.IOBase.close.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.