How to Implement __iter__ and __next__ in Python: Simple Guide
To implement
__iter__ and __next__ in Python, define __iter__ to return the iterator object itself and __next__ to return the next item or raise StopIteration when done. This makes your object usable in loops like for.Syntax
To make an object iterable, define two methods:
__iter__(self): Returns the iterator object itself. Usually, this isself.__next__(self): Returns the next item in the sequence. RaisesStopIterationwhen no more items are left.
python
class MyIterator: def __iter__(self): return self def __next__(self): # return next item or raise StopIteration pass
Example
This example shows a simple iterator that counts from 1 to 3. It demonstrates how __iter__ returns the object and __next__ returns the next number or stops iteration.
python
class CountToThree: def __init__(self): self.current = 1 def __iter__(self): return self def __next__(self): if self.current <= 3: number = self.current self.current += 1 return number else: raise StopIteration counter = CountToThree() for num in counter: print(num)
Output
1
2
3
Common Pitfalls
Common mistakes include:
- Not returning
selfin__iter__, which breaks the iterator protocol. - Forgetting to raise
StopIterationin__next__, causing infinite loops. - Modifying the iterable inside
__next__incorrectly, leading to wrong results.
python
class WrongIterator: def __iter__(self): # Wrong: returns a new object instead of self return [] def __next__(self): # Missing StopIteration return 1 # Correct version class RightIterator: def __init__(self): self.count = 0 def __iter__(self): return self def __next__(self): if self.count < 3: self.count += 1 return self.count else: raise StopIteration
Quick Reference
Remember these key points when implementing iterators:
__iter__must return the iterator object itself.__next__must return the next item or raiseStopIteration.- Use iterators to enable
forloops and other iterable contexts.
Key Takeaways
Implement __iter__ to return self to make your object an iterator.
Implement __next__ to return the next item and raise StopIteration when done.
Always raise StopIteration to signal the end of iteration.
Iterators let your objects work with for loops and other iterable contexts.
Avoid returning new objects in __iter__; return self instead.