Bird
Raised Fist0

Identify the error in this iterator implementation:

medium📝 Debug Q14 of Q15
Python - Magic Methods and Operator Overloading
Identify the error in this iterator implementation:
class MyIter:
    def __init__(self):
        self.data = [1, 2, 3]
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.index <= len(self.data):
            result = self.data[self.index]
            self.index += 1
            return result
        else:
            raise StopIteration
AThe condition should be <code>self.index < len(self.data)</code>
BMissing <code>return self</code> in __iter__
CShould raise <code>StopIteration</code> before returning result
DIndex should start at 1, not 0
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the index condition

    Index goes from 0 to len(data)-1. Using <= allows index == len(data), causing IndexError.
  2. Step 2: Correct the condition

    Change condition to self.index < len(self.data) to avoid out-of-range access.
  3. Final Answer:

    The condition should be self.index < len(self.data) -> Option A
  4. Quick Check:

    Index must be less than length to avoid error [OK]
Quick Trick: Use < to avoid index out of range errors [OK]
Common Mistakes:
MISTAKES
  • Using <= instead of < in index check
  • Forgetting to return self in __iter__
  • Starting index at 1 instead of 0

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes