Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Edge case: A helper collects items into a list using a default argument.

Edge case: A helper collects items into a list using a default argument.
def collect(x, out=[]):
    out.append(x)
    return out
a = collect(1)
b = collect(2, [])
c = collect(3)
print(a, b, c)
What is printed?
  1. A. [1] [2] [3]
  2. B. [1, 3] [2] [1, 3]
  3. C. [1] [2] [1, 3]
  4. D. [1, 3] [2] [3]

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

The default list is created once, when the function is defined, so the first and third calls share it: a and c are the same object, which holds [1, 3] by the time it is printed. The second call passes its own fresh list. Use out=None and create the list inside to avoid the bug.

More Coding Interview Problems questions

Exams that ask this topic