ProgrammingVery hardHCL · Tech Mahindra · Python placement

What does the following Python 3 code print? class Range2: def __init__(self, n): self.n = n def __getitem__(self, i): if i >= self.n: raise IndexError return i * i r = Range2(5) print([x for x in r])

  1. A. IndexError
  2. B. [0, 1, 2, 3, 4]
  3. C. [1, 4, 9, 16, 25]
  4. D. [0, 1, 4, 9, 16]

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

Without __iter__, Python falls back to calling __getitem__(0), __getitem__(1), ... until it raises IndexError, collecting i*i each time.

More Python Programming questions

Exams that ask this topic