What is the issue with the following code? ```python def add_to_inventory(item, inventory=[]): inventory.append(item) return inventory print(add_to_inventory("apple")) print(add_to_inventory("banana")) ```
💡 Model Answer
The function uses a mutable default argument (inventory=[]). In Python, default argument values are evaluated only once when the function is defined, not each time it is called. As a result, the same list object is reused across all calls. The first call appends "apple" to the list, and the second call appends "banana" to the same list, so both prints output ['apple', 'banana']. This can lead to unexpected behavior if callers expect a fresh list each time.
To fix it, use None as the default and create a new list inside the function:
def add_to_inventory(item, inventory=None):
if inventory is None:
inventory = []
inventory.append(item)
return inventoryNow each call gets its own list, producing ['apple'] and ['banana'] respectively.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500