CS FundamentalsHardProduct-company placement · Python

What does this code print?

What does this code print?
class Count:
    def __init__(s, n): s.i = 0; s.n = n
    def __iter__(s): return s
    def __next__(s):
        if s.i >= s.n: raise StopIteration
        s.i += 1
        return s.i

c = Count(3)
print(list(c), list(c), sum(Count(3)))
  1. A. [1, 2, 3] [1, 2, 3] 6
  2. B. [0, 1, 2] [] 3
  3. C. [1, 2, 3] [] 6
  4. D. [1, 2, 3] [] 0

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

__iter__ returns the object itself, so it is an iterator, not a re-iterable collection: the first list() exhausts it and the second finds it already at the end. A fresh Count(3) sums 1 + 2 + 3 = 6. A collection should return a new iterator from __iter__.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic