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])
- A. IndexError
- B. [0, 1, 2, 3, 4]
- C. [1, 4, 9, 16, 25]
- 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
- What does the following Python 3 code print? import itertools print(list(itertools.chain.fromiterable([[1, 2], [3], [4, 5, 6]])))
- What does the following Python 3 code print? import itertools print(list(itertools.product([1, 2], [3, 4])))
- What does the following Python 3 code print? import itertools print(list(itertools.combinationswithreplacement([1, 2, 3], 2)))
- What does the following Python 3 code print? import itertools print(list(itertools.compress([1, 2, 3, 4, 5], [1, 0, 1, 0, 1])))
- What does the following Python 3 code print? import itertools print(list(itertools.dropwhile(lambda x: x < 3, [1, 2, 3, 4, 1, 2])))
- What does the following Python 3 code print? import itertools print(list(itertools.takewhile(lambda x: x < 3, [1, 2, 3, 4, 1, 2])))