Why did a lazy iterator fail or read mutated data later?
Question
This code builds two lazy generator expressions: high over a list and rows over a stream opened inside with.
- Predict what
print(list(high))outputs afternumsis mutated,numsis rebound, andlimitchanges. - Predict what happens on
print(list(rows))afterload_lines(buf)returns. - Fix both cases so
highsnapshots[2, 3]right away andload_linesstreams lines safely while keeping the stream open until finished.
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)
- "WHAT RUNS IMMEDIATELY"
In
(x for x in nums if x > limit), Python evaluates the outermost iterablenumsat creation time. Theif x > limitcheck waits untilnext(). - "MUTATION VS REBINDING"
nums.append(4)changes the original list in place, whilenums = [99]points the namenumsat a different list. Which one doeshighsee? - "FILE CLOSES EARLY"
load_linesreturns a generator without reading a single line, sowith stream as f:closesfbefore the caller iterates. Useyieldinsidewithinstead.
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.
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)
[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 iterator | Evaluated 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 creation | high ignores [99] and keeps the original list |
limit = 2 | if 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:
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, orfilterfrom insidewith open(...) as f:. Exitingwithcloses 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, orclearcalls alter the output. - Assuming the outermost iterable is lazy too. Rebinding
nums = [99]does not redirecthigh, because Python evaluatednumsimmediately when creating the generator expression. - Materializing a huge multi-gigabyte file with
list(f)insidewithwhen you wanted streaming. Useyieldinsidewithor let the caller own thewith open(...)block.
Follow-up questions
- "What happens if the caller breaks out of
load_linesafter reading one line?" Thewithblock stays paused atyielduntil the generator closes. CPython closes it on garbage collection by throwingGeneratorExitso__exit__runs, but PyPy or reference cycles can delay that. Usewith contextlib.closing(load_lines(buf)) as rows:or let the caller open the file withwithfor immediate closing. - "What if a generator expression has two
forclauses?" Only the leftmostforiterable runs at creation time. Every innerforiterable,iffilter, and output expression runs lazily onnext(). In(x + y for x in a for y in b), rebindingalater has no effect, while rebindingbbefore iteration still changes the pairs produced. - "What happens if you mutate a
dictorsetwhile iterating lazily over it?" Unlike appending to a list, adding or removing keys in adictorsetduring iteration raisesRuntimeErrorbecause the container size changed mid-scan. Snapshot keys withlist(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 →