ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def g():
yield 1
yield 2
it = g()
for v in it:
print(v, end=" ")
break
for v in it:
print(v, end=" ")
print(list(it))- A. 1 2 []
- B. 1 1 2 []
- C. 1 2 [1, 2]
- D. 1 []
Correct answer: A. 1 2 []
break leaves the generator suspended after yielding 1; the second loop resumes it and gets 2, exhausting it. list() on an exhausted generator is [].
More Python Programming questions
- What is printed? python def g(): total = 0 while True: x = yield total if x is None: return total 100 total += x it = g() next(it)…
- What is printed? python def inner(): a = yield "x" b = yield "y" return (a, b) def outer(): r = yield from inner() yield r o = outer()…
- What is printed? python def g(): try: yield 1 yield 2 except KeyError: yield "caught" yield 3 it = g() print(next(it), it.throw(KeyError)…
- What is printed? python def g(): yield 1 raise StopIteration try: print(list(g())) except RuntimeError as e: print("RuntimeError")
- What is printed? python def g(): try: yield 1 finally: print("F", end=" ") it = g() next(it) it.close() print(next(it, "done"))
- What is printed? python import itertools a, b = itertools.tee(iter([1, 2, 3])) next(a); next(a) print(list(b), list(a))