What is the output of the following Python code and why?
💡 Model Answer
The code defines a function add_to_inventory that takes an item and an optional inventory list with a default value of an empty list. In Python, default argument values are evaluated only once when the function is defined, not each time it is called. Therefore, the same list object is reused across calls. The first call add_to_inventory('apple') appends 'apple' to the default list and returns ['apple']. The second call add_to_inventory('banana') appends 'banana' to the same list, so the returned list is ['apple', 'banana']. This explains why the output shows the accumulated items. The correct practice is to 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 = [] ... This ensures each call gets its own list and avoids unintended side‑effects.
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