ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def gen():
    yield 1
    return 5
    yield 2
it = gen()
print(list(it), next(it, 'done'))
  1. A. [1] 5
  2. B. [1, 5] done
  3. C. [1] done
  4. D. [1, 2] done

Correct answer: C. [1] done

list(it) consumes the generator until the return statement, which ends it without yielding 5, so the list is [1]. The generator is then exhausted, and next(it, 'done') gives the default.

More Python Programming questions

Exams that ask this topic