ProgrammingHardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
class Countdown:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        while self.n > 0:
            yield self.n
            self.n -= 2
c = Countdown(7)
print(list(c), list(c))
  1. A. [7, 5, 3, 1] [7, 5, 3, 1]
  2. B. [7, 5, 3, 1] []
  3. C. [7, 5, 3] []
  4. D. [7, 5, 3, 1] [1]

Correct answer: B. [7, 5, 3, 1] []

The loop mutates self.n, so after the first list the object is exhausted. A second iteration starts from n = -1 and yields nothing.

More Python Programming questions

Exams that ask this topic