ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def g():
    try:
        yield 1
        yield 2
    finally:
        print("cleanup", end=" ")

it = g()
print(next(it), end=" ")
it.close()
print(list(it))
  1. A. 1 cleanup []
  2. B. 1 [2]
  3. C. 1 cleanup [2]
  4. D. 1 [] cleanup

Correct answer: A. 1 cleanup []

close() raises GeneratorExit at the paused yield, so the finally block runs immediately and prints "cleanup". The generator is then finished; iterating it again yields nothing, so list(it) is []. Value 2 is never produced.

More Python Programming questions

Exams that ask this topic