ProgrammingHardTCS NQT pattern
What is printed?
What is printed?
def gen5():
for i in range(5):
if i == 3:
return
yield i
print(list(gen5()))- A. [0, 1, 2]
- B. [0, 1, 2, 3]
- C. [0, 1, 2, 3, 4]
- D. []
Correct answer: A. [0, 1, 2]
The loop yields 0, 1, 2; when i reaches 3 the return statement ends the generator immediately (raising StopIteration), so list() collects only [0, 1, 2].
More Python Programming questions
- What is printed? python def gen7(): try: yield 1 yield 2 finally: print("cleanup") g = gen7() print(next(g)) g.close()
- What is printed? python fs = [lambda i=i: i for i in range(3)] print([f() for f in fs])
- What is printed? python def outer(): funcs = [] x = 0 for i in range(3): x = x + i funcs.append(lambda: x) return funcs print([f() for f…
- What is printed? python adders = [] for i in range(3): def adder(x, i=i): return x + i adders.append(adder) print(adders[0](10)…
- What is printed? python x = 1 def outer2(): x = 2 def inner(): print(x) x = 3 return inner outer2()()
- What is printed? python counters = [] for i in range(3): j = i 2 counters.append(lambda: j) print([c() for c in counters])