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()))
  1. A. [0, 1, 2]
  2. B. [0, 1, 2, 3]
  3. C. [0, 1, 2, 3, 4]
  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

Exams that ask this topic