Bird
Raised Fist0

Given this iterator implementation in Python, identify the bug:

medium📝 Analysis Q14 of Q15
LLD - Behavioral Design Patterns — Part 1

Given this iterator implementation in Python, identify the bug:

class BuggyIterator:
    def __init__(self, data):
        self.data = data
        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

What is the cause of the error when iterating?

AIndexError due to accessing out-of-range element
BStopIteration raised too early
CInfinite loop because index never increments
DSyntax error in method definitions
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the condition in __next__

    The condition uses <= len(self.data), which allows index to equal length, causing out-of-range access.
  2. Step 2: Understand the error caused

    Accessing self.data[self.index] when index == len(self.data) causes IndexError because list indices go from 0 to len-1.
  3. Final Answer:

    IndexError due to accessing out-of-range element -> Option A
  4. Quick Check:

    Condition allows index == length causing IndexError [OK]
Quick Trick: Use < not <= to avoid out-of-range errors [OK]
Common Mistakes:
MISTAKES
  • Using <= instead of < in boundary check
  • Assuming StopIteration triggers before error
  • Ignoring index increment effects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes