ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def g():
    try:
        yield 1
        yield 2
    finally:
        print('cleanup')
it = g()
print(next(it))
it.close()
print(list(it))
  1. A. 1 | cleanup | []
  2. B. 1 | 2 | []
  3. C. 1 | cleanup | [1, 2]
  4. D. 1 | 2 | cleanup

Correct answer: A. 1 | cleanup | []

close() raises GeneratorExit at the paused yield, so the finally block runs and prints cleanup. A closed generator yields nothing more, so list gives [].

More Python Programming questions

Exams that ask this topic