ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def outer():
    fs = []
    for i in range(3):
        def f(j=None):
            return i if j is None else j
        fs.append(f)
        if i == 1:
            break
    return [f() for f in fs], i
print(outer())
  1. A. ([0, 1], 1)
  2. B. ([2, 2], 2)
  3. C. ([1, 1], 1)
  4. D. ([1, 1, 1], 1)

Correct answer: C. ([1, 1], 1)

The loop breaks at i = 1, so two closures were created and i stays 1. Both closures read the same variable i when called, giving 1 each.

More Python Programming questions

Exams that ask this topic