ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
class R:
    def __init__(self, n): self.n = n
    def __len__(self): return self.n
    def __getitem__(self, i):
        if i >= self.n: raise IndexError
        return i * i
r = R(4)
print(list(r), 9 in r, list(reversed(r)), bool(R(0)))
  1. A. TypeError
  2. B. [0, 1, 4, 9] False [9, 4, 1, 0] False
  3. C. [0, 1, 4, 9] True [9, 4, 1, 0] True
  4. D. [0, 1, 4, 9] True [9, 4, 1, 0] False

Correct answer: D. [0, 1, 4, 9] True [9, 4, 1, 0] False

Without __iter__, Python iterates by calling __getitem__ with 0, 1, 2, ... until IndexError, and `in` uses that iteration. reversed() works with __len__ + __getitem__. Truth value falls back to __len__.

More Python Programming questions

Exams that ask this topic