ProgrammingHardAccenture pattern

What is printed?

What is printed?
class Idx:
    def __index__(self):
        return 3
l = [0, 1, 2, 3, 4, 5]
print(l[Idx()])
  1. A. TypeError
  2. B. 3
  3. C. Idx()
  4. D. IndexError

Correct answer: B. 3

__index__ lets a custom object be used anywhere an integer index is required, such as list subscripting; Python calls it to get 3, so l[Idx()] is the same as l[3], which is 3.

More Python Programming questions

Exams that ask this topic