The Iterator Protocol
Swipe to show menu
In Python, the iterator protocol is a set of methods that allows objects to be iterated over, making them compatible with constructs like for loops. The two essential methods involved are __iter__ and __next__. When you use a for loop on an object, Python internally calls the object's __iter__ method to retrieve an iterator. This iterator must have a __next__ method, which returns the next item in the sequence each time it is called. When there are no more items, __next__ must raise a StopIteration exception to signal the end of the sequence.
1234567891011121314151617181920212223242526class SquaresIterator: # Initialize with the number of squares to generate def __init__(self, limit): self.limit = limit self.current = 0 # Return the iterator object (itself) def __iter__(self): return self # Return the next square, or stop if done def __next__(self): if self.current < self.limit: # Calculate square result = self.current ** 2 # Move to next number self.current += 1 return result # If no more items else: raise StopIteration for square in SquaresIterator(5): print(square)
__init__ - Setup Phase
When the iterator is created it receives a:
-
limit→ how many numbers to generate; -
It sets
current = 0→ the starting point; -
It prepares everything needed for iteration.
__iter__ - Making It Iterable
- Returns
self(the object itself); - This is what allows you to use it in a for loop.
__next__ - Producing Values
This method runs every time the loop asks for the next item:
- If
current<limit:- Calculate
current²; - Increase
currentby 1; - Return the result.
- Calculate
- If
current≥limit:- Raise
StopIterationto stop the loop automatically.
- Raise
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat