ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
class Counter:
def __init__(self, n):
self.n = n
def __iter__(self):
self.i = 0
return self
def __next__(self):
if self.i >= self.n:
raise StopIteration
self.i += 1
return self.i
c = Counter(3)
print(list(c), list(c))- A. [1, 2, 3] []
- B. [1, 2, 3] [1, 2, 3]
- C. [0, 1, 2] [0, 1, 2]
- D. [] [1, 2, 3]
Correct answer: B. [1, 2, 3] [1, 2, 3]
Unlike a plain generator, __iter__ here resets self.i = 0 every time iteration starts, so each list(c) call restarts the count from scratch and both produce [1, 2, 3].
More Python Programming questions
- What is printed? python class Box: def init(self, items): self.items = items def len(self): return len(self.items) def contains(self, x)…
- What is printed? python class D: def getitem(self, key): if isinstance(key, slice): return f"slice {key.start}:{key.stop}:{key.step}"…
- What is printed? python try: try: 1 / 0 except ZeroDivisionError: raise RuntimeError("r") except RuntimeError as e: print(e…
- What is printed? python try: raise ValueError("x") from None except ValueError as e: print(e.cause, e.suppresscontext)
- What is printed? python try: try: raise KeyError("k") except ValueError: print("vl") except KeyError: print("kl")
- What is printed? python x = 5 print(f"{x=}")