Iterable & Iterator Protocol (__iter__ & __next__)
1Concept
An Iterable is an object providing an `__iter__()` method that returns an Iterator. An Iterator implements `__next__()` to return subsequent elements and raises `StopIteration` when exhausted.
2Architecture Diagram
[ Iterable Object ] ---> .__iter__() ---> [ Iterator Object ] ---> .__next__() ---> Item 1
---> .__next__() ---> Item 2
---> .__next__() ---> StopIteration3Code Example
Python 3.12
class FibonacciIterator:
def __init__(self, limit: int):
self.limit = limit
self.count = 0
self.a, self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
if self.count >= self.limit:
raise StopIteration
val = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return val
fib = FibonacciIterator(6)
print(f"Fibonacci Sequence: {list(fib)}")4Expected Output
Fibonacci Sequence: [0, 1, 1, 2, 3, 5]
5Key Takeaways
- ✓An iterator is exhausted after a single complete traversal.
- ✓The `for` loop catches `StopIteration` automatically behind the scenes.
- ✓Iterators consume O(1) memory regardless of sequence length.