How to Make Object Iterable in Python: Simple Guide
To make an object iterable in Python, define the
__iter__ method that returns an iterator object, which itself implements the __next__ method. This allows the object to be used in loops and other iterable contexts.Syntax
To make an object iterable, implement the __iter__ method that returns an iterator. The iterator must implement the __next__ method, which returns the next item or raises StopIteration when done.
__iter__(self): Returns the iterator object (usuallyself).__next__(self): Returns the next value or raisesStopIteration.
python
class MyIterable: def __iter__(self): return self # returns the iterator object def __next__(self): # return next item or raise StopIteration raise StopIteration
Example
This example shows a class that counts from 1 to 3, making it iterable with for loops.
python
class Counter: def __init__(self, limit): self.limit = limit self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.limit: self.current += 1 return self.current else: raise StopIteration counter = Counter(3) for number in counter: print(number)
Output
1
2
3
Common Pitfalls
Common mistakes include:
- Not raising
StopIterationin__next__, causing infinite loops. - Returning a new iterator in
__iter__each time, which can reset iteration unexpectedly. - Not implementing
__iter__at all, so the object is not iterable.
python
class WrongIterable: def __iter__(self): return self def __next__(self): return 1 # never raises StopIteration, infinite loop # Correct way class RightIterable: 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
Summary tips to make an object iterable:
- Implement
__iter__to return an iterator. - Iterator must implement
__next__to return next item or raiseStopIteration. - Use
forloops to automatically use these methods. - Reset iteration state carefully if needed.
Key Takeaways
Implement __iter__ to return an iterator object for your class.
The iterator must implement __next__ to provide items and raise StopIteration when done.
Without raising StopIteration, iteration will never stop and cause errors.
Use for loops to automatically iterate over your custom iterable objects.
Reset iteration state carefully if your object is reused in multiple loops.