ProgrammingHardGATE CS · Product-company placement

What is printed?

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

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

An iterator whose __iter__ returns self can be consumed only once; the second list() resumes the exhausted object (i keeps growing past 3) and gets nothing.

More Python Programming questions

Exams that ask this topic