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()])- A. TypeError
- B. 3
- C. Idx()
- 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
- What is printed? python def f(a, b={"x": 1}): b["x"] += a return b print(f(1)) print(f(2))
- What is printed? python def f2(x, y, , z=None): if z is None: z = [] z.append(x + y) return z print(f2(1, 2)) print(f2(3, 4))
- What is printed? python a = {1, 2, 3} b = a b.add(4) c = a.copy() c.add(5) print(a, c)
- What is printed? python class Meta: shared = [] def init(self, x): self.shared.append(x) m1 = Meta(1) m2 = Meta(2) print(m1.shared…
- What is printed? python def outer(): data = [1, 2, 3] def modify(): data.append(4) modify() return data print(outer())
- What is printed? python a, b = 1, 2 a, b = b, a + b print(a, b)