ProgrammingHardAccenture pattern

What is printed?

What is printed?
def outer():
    data = [1, 2, 3]
    def modify():
        data.append(4)
    modify()
    return data
print(outer())
  1. A. [1, 2, 3]
  2. B. [1, 2, 3, 4]
  3. C. UnboundLocalError
  4. D. [4]

Correct answer: B. [1, 2, 3, 4]

modify mutates the enclosing list in place via .append (no reassignment of the name data is needed, so no nonlocal declaration is required). The closure's append is visible when outer returns data.

More Python Programming questions

Exams that ask this topic