Editor

Fix the Broken Iterator

Intermediate · Fix the bug · from Python Iterators: How for Loops Really Work Under the Hood

From the lesson: Why Is Lazy Evaluation So Powerful?

Iterators are lazy - they produce values one at a time, only when asked. This is the opposite of a list, which stores everything in memory at once.

Read this part of the lesson

This Squares iterator should yield 1, 4, 9, 16, 25 (squares of 1 through 5). But it has two bugs. Find and fix them.

class Squares:
    def __init__(self, n):
        self.n = n
        self.current = 0

    def __iter__(self):
        return Squares(self.n)

    def __next__(self):
        self.current += 1
        if self.current > self.n:
            raise StopIteration
        return self.current * 2
class Squares:
def __init__(self, n):
self.n = n
self.current = 0
def __iter__(self):
return Squares(self.n) # Bug 1: creates a NEW object every time
def __next__(self):
self.current += 1
if self.current > self.n:
raise StopIteration
return self.current * 2 # Bug 2: wrong formula for squaring
for s in Squares(5):
print(s)

More Iterator exercises

All Python exercises · 50 practice problems · Advanced Python quiz