Data Structures & AlgorithmsHardTCS NQT Digital · Python semantics

Problem: What does the following print?

Problem: What does the following print?
def add(x, bucket=[]):
    bucket.append(x)
    return bucket
add(1)
add(2)
print(add(3))
  1. A. [3]
  2. B. [1, 2, 3]
  3. C. [1, 2]
  4. D. [2, 3]

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

The default list is created once and shared between calls, so all three appends land in the same list. Assuming a fresh list each call is the classic Python trap.

More Coding Interview Problems questions

Exams that ask this topic