ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def f():
    try:
        return [1]
    finally:
        pass
def g():
    x = [1]
    try:
        return x
    finally:
        x.append(2)
def h():
    x = 1
    try:
        return x
    finally:
        x = 2
print(f(), g(), h())
  1. A. [1] [1] 1
  2. B. [1] [1, 2] 2
  3. C. [1] [1, 2] 1
  4. D. [1] [1] 2

Correct answer: C. [1] [1, 2] 1

The return value is computed before finally runs. Mutating the returned list in finally is visible (same object), but rebinding the local name x afterwards does not change what was already chosen to be returned.

More Python Programming questions

Exams that ask this topic