ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
class Counter:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        self.i = 0
        return self
    def __next__(self):
        if self.i >= self.n:
            raise StopIteration
        self.i += 1
        return self.i
c = Counter(3)
print(list(c), list(c))
  1. A. [1, 2, 3] []
  2. B. [1, 2, 3] [1, 2, 3]
  3. C. [0, 1, 2] [0, 1, 2]
  4. D. [] [1, 2, 3]

Correct answer: B. [1, 2, 3] [1, 2, 3]

Unlike a plain generator, __iter__ here resets self.i = 0 every time iteration starts, so each list(c) call restarts the count from scratch and both produce [1, 2, 3].

More Python Programming questions

Exams that ask this topic