What will be the output of the following Python program?

def add_item(x, items=[]):
    items.append(x)
    return items

print(add_item(1))
print(add_item(2))
                        

Options

  • A. [1] and [2]
  • B. [1] and [1, 2]
  • C. [1, 2] and [1, 2]
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. [1] and [1, 2]

Detailed Explanation

Default mutable arguments are created only once when the function is defined. The same list is reused across function calls.