In this lesson, you will learn how to maintain internal object state to track progress across multiple calls to the next() function during manual iteration.
The Problem of Lost Progress
When you implement a custom iterator, Python doesn't automatically know where you left off. Every time next() is called on your object, your code must "remember" the current position. If your iterator doesn't track this state explicitly, it will either restart from the beginning every time or trigger an error.
Maintaining Internal State
To manage state, we use instance attributes (typically defined in __init__) that serve as a "bookmark." This bookmark acts as a pointer that updates every time next() is invoked.
Consider a simple custom iterator that counts down from a specific number:
class Countdown:
def __init__(self, start):
self.current = start # Our internal state/bookmark
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
# Update the state before returning the value
value = self.current
self.current -= 1
return value
In this example, self.current is the state. Because it lives on the object instance, it persists between calls to __next__(). When you run next(my_countdown), the object executes the logic, decrements the state, and pauses. The next time you call next(), the object doesn't start at the original start value; it resumes exactly where self.current left off.
Why State Matters
Managing this state manually is what allows complex objects to behave like simple sequences. By updating your pointer (self.current) inside __next__, you ensure that the iteration flows linearly through your data without needing to store the entire sequence in memory at once. This keeps your memory overhead low while providing full control over how you navigate through your custom data structures.
Key Takeaway: To track progress in manual iteration, store your current position as an instance attribute and update it within the __next__ method before returning each subsequent value.