ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
def countdown(n):
while n > 0:
yield n
n -= 1
g = countdown(3)
print(list(g))
print(list(g))- A. [3, 2, 1] [3, 2, 1]
- B. [3, 2, 1] []
- C. [1, 2, 3] []
- D. [] [3, 2, 1]
Correct answer: B. [3, 2, 1] []
The first list(g) drives the generator to exhaustion, collecting 3, 2, 1. A generator cannot be restarted: the second list(g) finds it already finished and returns an empty list.
More Python Programming questions
- What is printed? python it = iter([1, 2, 3]) print(next(it), next(it)) for x in it: print("loop", x) print(list(it))
- What is printed? python def flatten(lst): for item in lst: if isinstance(item, list): yield from flatten(item) else: yield item…
- What is printed? python g = (x for x in range(3)) print(sum(g), sum(g))
- What is printed? python def gen5(): for i in range(5): if i == 3: return yield i print(list(gen5()))
- 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])