ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
def outer():
    x = []
    def appendVal(v):
        x.append(v)
        return x
    return appendVal
f1 = outer()
f2 = outer()
print(f1(1), f1(2), f2(3))
  1. A. [1, 2] [1, 2] [1, 2, 3]
  2. B. [1] [1, 2] [3]
  3. C. [1, 2] [1, 2] [3]
  4. D. [1, 2, 3] [1, 2, 3] [1, 2, 3]

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

Each call to outer() creates its OWN fresh list x. f1 and f2 are closures over two separate lists, so f1's calls share and grow one list ([1], then [1,2]), while f2's call starts its own fresh list ([3]).

More Python Programming questions

Exams that ask this topic