Python Iterator Exhaustion: Why the Second Loop Is Empty
Fix exhausted Python iterators and generators. Compare materializing values, fresh generator factories and itertools.tee with a runnable consumption lab.
If a Python generator produces rows once and an empty result the next time, the rows may already have been consumed. An iterator represents progress through a sequence of values. Asking for another iterator from that iterator does not reset it. The repair depends on what you need: a stored collection for replay, a producer that can genuinely run again, or coordinated branches over one source. This guide makes those choices observable with a bounded, executable lab.
Start by locating the first consumer
A reporting function calculates a total, then loops over the same rows to render details. With a list, both operations work. After a refactor changes rows into a generator expression, the total still looks correct while the detail section becomes empty. The total calculation already traversed the stream.
The short example below reproduces that behavior without a file, database or asynchronous operation. The source values are invented integers. The empty second list is the expected result of using the same exhausted generator, rather than evidence that the original values disappeared from some external system.
Look upstream before changing the final loop. Logging a list of rows, checking membership, taking a preview or passing rows to another helper can all advance an iterator. The debugging question is which object each consumer receives and how far that object has progressed.
rows = (value for value in [3, 5, 7])
print(sum(rows)) # 15
print(list(rows)) # []
print(iter(rows) is rows) # TrueAn iterable can supply an iterator; an iterator tracks progress
A list is an iterable that can supply independent iterators. Calling iter(values) twice creates two separate cursors over the same list. Advancing one cursor does not advance the other. The fixture tests that both cursors initially yield the same first item while having different identities.
An iterator implements the next-item operation and returns itself from iter(). Assigning it to another name also retains the same object. In the lab, alias and first therefore advance one shared cursor. Neither assignment nor iter(first) creates a new traversal.
Once a conforming iterator raises StopIteration, later requests must keep reporting exhaustion. next(cursor, marker) lets the test observe that state without an exception escaping the test. This is different from temporarily having no new data in a live feed: the synchronous iterator protocol uses StopIteration to indicate the traversal is finished.
An iterator can be partly consumed before it becomes empty
The lab previews two values from a three-value iterator with islice. The later consumer receives only the remaining third value. A preview is still consumption; islice limits how much it requests but does not rewind the source afterward.
any stops when it finds a truthy item. On the fixture [0, 5, 9], it consumes zero and five, returns True and leaves nine for the next consumer. A successful membership search also consumes through the matching item: checking whether two is in an iterator over [1, 2, 3, 4] leaves [3, 4]. These operations can change later behavior even when they return only a Boolean.
This matters for validation helpers. A helper that accepts arbitrary Iterable input and checks one condition may silently consume part of a generator supplied by its caller. Make that ownership explicit: either document consumption, accept a collection when repeated traversal is required, or return a replacement stream together with any inspected result.
Materialize once when repeated traversal should use the same values
When the data set is finite and fits the application’s memory budget, list(source) stores the remaining values. Later loops iterate over that stored collection. Do this before the first consumer if both consumers need the complete data; materializing an already partly consumed iterator cannot recover the missing prefix.
The lab’s cached list is traversed repeatedly without running its producer again. This gives replay of the stored values, which can be useful when a total and a detailed report must agree. It is not a transaction or a deep snapshot of a database, and storing references to mutable rows does not freeze those rows.
Do not materialize an unbounded source simply to make a second loop work. Decide whether your operation has a bounded batch, can calculate the required outputs in one pass, or needs an external spool. A small successful demonstration provides no evidence about the memory cost of your real data.
| Need | Suitable approach | Main tradeoff |
|---|---|---|
| Repeat the same finite values | Materialize before consumption | Memory proportional to stored values |
| Re-run a repeatable producer | Call a fresh producer for each pass | Repeated work and possibly different source data |
| Branch one traversal | Use tee with a bounded consumer gap | Buffered values while consumers diverge |
| Inspect a prefix then continue | Replay the prefix with chain | Replacement stream still has one traversal |
A generator function can create a fresh execution
Calling the make_rows generator function returns a generator object. Its body begins when that object is advanced. The fixture records when the body starts: merely calling make_rows does not add an entry, consuming it adds one, and consuming the same exhausted object does not run the body again.
Calling make_rows again creates another generator and can produce the same fixture values again. That works because this producer starts from a repeatable tuple on every invocation. A callable that merely returns an existing iterator is not a fresh producer. The bad_factory example returns its captured iterator twice, so the second result is empty.
Rerunning a real producer can repeat queries, file reads or side effects. It can also return changed data. If you need identical values for two passes, a producer factory alone does not establish that requirement. Choose between recomputation and stored replay deliberately, and test the source consistency guarantees you actually have.
tee separates cursor positions by retaining values
itertools.tee supplies multiple iterators over one input traversal. In the fixture, the left branch moves four items ahead. The right branch can then read earlier values without making the source produce them a second time. Instrumentation records source pulls rather than trying to infer internal buffer size from process memory.
The distinction is important: tee does not rerun the producer or make an independent deep copy of every row. The mutable-dictionary fixture changes a labels list through one branch and observes that change through the other. Branches can have separate positions while still yielding references to the same objects.
Consumer skew can require substantial auxiliary storage. A branch that never catches up can keep earlier values needed by that branch buffered as the other continues. The official documentation also cautions that tee iterators are not threadsafe. The sequential lab does not test concurrent access or measure memory usage.
After splitting, use the returned branches rather than advancing the original input separately. If one branch will read the entire finite source before the other begins, materializing once may be easier to reason about. tee is a coordination tool, not a way to obtain unlimited replay at constant memory cost.
Run the complete consumption and replay lab
Save this program as iterator_lab.py and run python3 iterator_lab.py with Python 3.12 or later. The exact published listing was executed on Python 3.12.14. It uses only the standard library, bounded integer lists and one invented dictionary; it makes no network requests and opens no files.
Expected output is PASS: 168 checks; consumption, replay and tee behavior verified. Of those checks, 135 come from testing every consumed prefix for source lengths zero through eight. The matrix compares the consumed prefix and remaining suffix against ordinary list slicing, then verifies that another traversal is empty.
The remaining checks cover cursor identity, aliases, persistent exhaustion, sum, islice, any, membership, generator-body timing, fresh and faulty factories, stored replay, tee source pulls, shared mutable rows and explicit prefix replay. They demonstrate defined local behavior rather than throughput or memory benchmarks.
"""Python 3.12+; invented bounded data; no external dependencies."""
from itertools import chain, islice, tee
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def main():
values = [2, 4, 6]
first, second = iter(values), iter(values)
check(first is not second, 'list supplies independent cursors')
check(next(first) == 2 and next(second) == 2, 'both start at beginning')
check(iter(first) is first, 'iterator returns itself')
alias = first
check(next(alias) == 4 and next(first) == 6, 'aliases share progress')
for _ in range(3):
marker = object()
check(next(first, marker) is marker, 'exhaustion remains terminal')
check(list(values) == [2, 4, 6], 'source list remains populated')
stream = (x for x in [3, 5, 7])
check(sum(stream) == 15, 'first reduction consumes all')
check(list(stream) == [], 'second consumer sees exhausted stream')
stream = iter([10, 20, 30])
preview = list(islice(stream, 2))
check(preview == [10, 20] and list(stream) == [30], 'preview consumes prefix')
stream = iter([0, 5, 9])
check(any(stream) is True, 'any stops at first truthy item')
check(list(stream) == [9], 'matching item consumed too')
stream = iter([1, 2, 3, 4])
check(2 in stream, 'membership scans through matching item')
check(list(stream) == [3, 4], 'membership changes later traversal')
runs = []
def make_rows():
runs.append('started')
yield from (2, 4, 6)
g = make_rows()
check(runs == [], 'generator body not entered at function call')
check(sum(g) == 12 and runs == ['started'], 'first consumption runs body')
check(sum(g) == 0 and len(runs) == 1, 'exhausted generator not rerun')
check(sum(make_rows()) == 12 and len(runs) == 2, 'fresh call creates new execution')
cached = list(make_rows())
check(sum(cached) == 12 and list(cached) == [2, 4, 6], 'materialized values replay')
check(len(runs) == 3, 'replaying list does not rerun producer')
existing = iter([8, 9])
bad_factory = lambda: existing
check(list(bad_factory()) == [8, 9], 'first bad factory use')
check(list(bad_factory()) == [], 'callable can return same exhausted iterator')
pulled = []
def source():
for value in range(6):
pulled.append(value)
yield value
left, right = tee(source())
check(pulled == [], 'tee does not eagerly drain source')
check(list(islice(left, 4)) == [0, 1, 2, 3], 'leading tee branch advances')
check(pulled == [0, 1, 2, 3], 'source produced four items')
check(list(islice(right, 2)) == [0, 1], 'lagging branch replays earlier values')
check(pulled == [0, 1, 2, 3], 'replay did not rerun source')
check(list(left) == [4, 5], 'leading branch finishes')
check(list(right) == [2, 3, 4, 5], 'lagging branch catches up')
row = {'labels': []}
a, b = tee(iter([row]))
next(a)['labels'].append('shared')
check(next(b)['labels'] == ['shared'], 'tee does not deep copy rows')
stream = iter([0, 1, 2])
head = list(islice(stream, 1))
restored = chain(head, stream)
check(list(restored) == [0, 1, 2], 'explicit prefix replay keeps zero')
check(list(restored) == [], 'chain itself remains one pass')
# A deterministic small matrix: compare every possible consumed prefix.
for size in range(9):
expected = list(range(size))
for prefix in range(size + 1):
cursor = iter(expected)
check(list(islice(cursor, prefix)) == expected[:prefix], 'prefix partition')
check(list(cursor) == expected[prefix:], 'remaining partition')
check(list(cursor) == [], 'second traversal empty')
print(f'PASS: {checks} checks; consumption, replay and tee behavior verified')
if __name__ == '__main__':
main()If you inspect a prefix, return a replacement stream
The final fixed-size example collects one item with islice, then chains that saved prefix in front of the remaining cursor. The resulting stream yields the entire fixture sequence, including zero. Using a stored list for the prefix avoids confusing a valid falsey value with an empty source.
Consumers must use the returned chain. Continuing with the original cursor skips the saved prefix, and iterating over the chain twice still leaves the second traversal empty. This approach repairs one deliberate inspection boundary; it does not convert an iterator into a reusable collection.
If the prefix contains mutable objects, replaying it retains those references. If the producer owns a file or another resource, the replacement stream also does not take care of that resource’s lifetime automatically. Keep the source open for the required traversal and close it according to the producer’s contract.
Do not interpret lazy as nothing happens at construction
For a generator function, the body waits until iteration begins. Generator expressions have an additional detail: their leftmost iterable expression is evaluated and its iterator obtained when the expression is constructed. The element expression and subsequent work are evaluated as items are requested.
That distinction can affect where an exception appears. It also explains why wrapping an already-created one-pass cursor in a generator expression does not make its source repeatable. The new generator still pulls from that same cursor. Read the producer boundary as well as the visible parentheses.
Choose a repair that preserves the caller’s contract
A useful regression test should invoke the real sequence of consumers. Test the total followed by rendering, validation followed by export, or preview followed by processing. A test that creates a fresh generator independently for each assertion may hide the bug the application actually has.
Include empty input and partial consumption. A completely exhausted stream is easy to recognize; a partly consumed stream can produce a plausible but incomplete report. Where the function consumes caller-supplied input, state that behavior in its API documentation and test that no earlier helper silently takes ownership.
This guide covers synchronous sequential iterators. Async iterators, database cursors, file seeking and resource cleanup have additional contracts that the lab does not verify. For the ordinary two-pass bug, first identify the consumed object, then decide whether the application needs stored values, a fresh execution or coordinated branches. The repair should express that decision rather than attempting to reset an exhausted iterator.
Your next steps
- iter(iterator) and another variable name share progress; neither restarts traversal.
- Materialize before consumption for stored replay, or call a genuinely fresh producer when repeated execution is acceptable.
- tee coordinates separate positions over one source and can retain buffered references; test consumer skew and ownership.
Sources & official resources
Linked resources checked on 2026-11-01. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →