ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def f():
    x = 0
    def inc():
        nonlocal x
        x += 1
        return x
    return [inc() for _ in range(3)], x
print(f())
  1. A. ([1, 2, 3], 0)
  2. B. ([1, 2, 3], 3)
  3. C. ([1, 1, 1], 3)
  4. D. ([1, 1, 1], 0)

Correct answer: B. ([1, 2, 3], 3)

The tuple elements are evaluated left to right: the comprehension runs inc three times first (each call updating the shared cell), so by the time x is read it is already 3.

More Python Programming questions

Exams that ask this topic