ProgrammingModerateProduct-company MCQ pattern

What is printed?

What is printed?
def add(item, bucket=[]):
    bucket.append(item)
    return bucket
a = add(1)
b = add(2)
c = add(3, [])
print(a, b, c, a is b)
  1. A. [1] [2] [3] False
  2. B. [1] [1, 2] [3] False
  3. C. [1, 2] [1, 2] [1, 2, 3] True
  4. D. [1, 2] [1, 2] [3] True

Correct answer: D. [1, 2] [1, 2] [3] True

The default list is created once, when def runs, and shared by every call that omits the argument. a and b are the same list, which now holds [1, 2]. Passing a fresh list for c avoids the sharing. Use bucket=None and create the list inside.

More Python Programming questions

Exams that ask this topic