Exhaustion of a One-Pass Iterator
An iterator can consume its source as it advances. Reusing an exhausted iterator yields no new items under the normal iterator protocol.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Trace two consumers
If an iterator produces 3 and 5, summing it consumes both and gives eight. Counting it immediately afterward can give zero. An iterable collection may produce an independent iterator for each pass. Input, state, and output identifies the position that changes during consumption.
Choose how to share work
A report needing both count and sum can accumulate them together in one loop. Retain a copy when a genuine second traversal is required and the data fits in memory. A running average demonstrates a computation requiring only small retained state.[1]
Trace a shared cursor through two names
After walk = iter([5, 7, 11]), calling next(walk) produces five. Assign other = walk and call next(other). The result is seven because both names refer to the same cursor. Converting walk to a list now produces [11] and consumes the last item. A subsequent conversion produces an empty list. In contrast, calling iter twice on the original list creates two independent cursors. This example tests the difference between an iterable that can supply new iterators and an iterator with its own progress. The same distinction matters when iterating over file lines.
Choose replay explicitly in a two-pass algorithm
Suppose one loop totals amounts and another computes each amount as a percentage of the total. Reading a generator in the first loop consumes it, so the second loop cannot do the calculation. If the source is small, preserve a list when obtaining it. If it is large and stable, a callable that reopens the source might be better. An externally changing source can produce inconsistent passes unless both reads use the same snapshot. Add a test that passes a generator expression rather than an ordinary list. A streaming running average serves a different purpose and can be maintained with constant retained state.