CodexBloom - Programming Q&A Platform

Python 2.7: How to correctly implement a custom iterator that handles StopIteration gracefully?

👀 Views: 176 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-26
python-2.7 iterator stopiteration python

I tried several approaches but none seem to work. I've looked through the documentation and I'm still confused about I'm relatively new to this, so bear with me. I'm trying to implement a custom iterator in Python 2.7, and I'm running into issues with how to handle the `StopIteration` exception properly. My iterator is supposed to yield items from a list, but I want to ensure that it can handle the situation where the list is exhausted without crashing or throwing an behavior. Currently, my code looks like this: ```python class MyIterator(object): def __init__(self, data): self.data = data self.index = 0 def __iter__(self): return self def next(self): if self.index >= len(self.data): raise StopIteration result = self.data[self.index] self.index += 1 return result ``` When I try to iterate through it using a `for` loop, it seems to work fine. However, when I call `next()` directly, I encounter the following behavior when the iterator is exhausted: ``` Traceback (most recent call last): File "test.py", line 10, in <module> print(iterator.next()) StopIteration ``` I want it to handle the `StopIteration` gracefully when using `next()` without the need for `try`/`except` blocks in the calling code. Is there a preferred pattern or best practice for implementing iterators in Python 2.7 to achieve this behavior? Any advice or examples would be greatly appreciated. I'd really appreciate any guidance on this. Am I missing something obvious? Any ideas what could be causing this?