ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
class It:
def __init__(self): self.i = 0
def __iter__(self): return self
def __next__(self):
self.i += 1
if self.i > 3: raise StopIteration
return self.i
x = It()
print(list(x), list(x), sum(It()))- A. [1, 2, 3] [1, 2, 3] 6
- B. [1, 2, 3] [] 6
- C. [1, 2, 3] [] 0
- D. [1, 2, 3] [4] 6
Correct answer: B. [1, 2, 3] [] 6
An iterator whose __iter__ returns self can be consumed only once; the second list() resumes the exhausted object (i keeps growing past 3) and gets nothing.
More Python Programming questions
- What is printed? python class Ctx: def init(self, n): self.n = n def enter(self): print("in", self.n, end=" ") return self.n 10 def…
- What is printed? python from contextlib import contextmanager @contextmanager def cm(): print("A", end=" ") try: yield "B" except…
- What is printed? python from itertools import accumulate, chain, islice, count print(list(accumulate([1, 2, 3, 4])), list(chain("ab"…
- What is printed? python from itertools import ziplongest, product, combinations, permutations print(list(ziplongest("ab", [1, 2, 3]…
- What is printed? (Output lines are shown separated by " / ".) python from itertools import groupby data = [1, 1, 2, 1, 3, 3] print([(k…
- What is printed? python from functools import reduce print(reduce(lambda a, b: a 10 + b, [1, 2, 3]), reduce(lambda a, b: a + b, [], 7)…