How to Create Custom Iterator in Python: Simple Guide
To create a custom iterator in Python, define a class with
__iter__ method returning the iterator object and a __next__ method that returns the next item or raises StopIteration when done. This lets you control how your object is looped over in for loops or other iteration contexts.Syntax
To create a custom iterator, define a class with these 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 the iterator object return self def __next__(self): # Return the next item or raise StopIteration pass
Example
This example creates an iterator that returns numbers from 1 to 5. It shows how __iter__ and __next__ work together to produce values one by one.
python
class CountToFive: def __init__(self): self.current = 1 def __iter__(self): return self def __next__(self): if self.current <= 5: number = self.current self.current += 1 return number else: raise StopIteration # Using the custom iterator for num in CountToFive(): print(num)
Output
1
2
3
4
5
Common Pitfalls
Common mistakes when creating custom iterators include:
- Not raising
StopIterationwhen the sequence ends, causing infinite loops. - Forgetting to return
selfin__iter__. - Modifying the iteration state incorrectly, leading to skipped or repeated items.
Here is a wrong and right way example:
python
# Wrong: __iter__ does not return self class WrongIterator: def __iter__(self): return [] # Should return self def __next__(self): raise StopIteration # Right: class RightIterator: def __iter__(self): return self def __next__(self): raise StopIteration
Quick Reference
| Method | Purpose |
|---|---|
| __iter__(self) | Returns the iterator object (usually self) |
| __next__(self) | Returns the next item or raises StopIteration |
| StopIteration | Exception to signal no more items |
Key Takeaways
Define __iter__ to return the iterator object itself.
Define __next__ to return the next item or raise StopIteration when done.
Always raise StopIteration to end iteration cleanly.
Use your custom iterator in for loops or any iteration context.
Test your iterator to avoid infinite loops or missing items.