Home › Interview Questions › What will be the output of the following Python co…

What will be the output of the following Python code? ```python def add_to_inventory(item, inventory=[]): inventory.append(item) return inventory print(add_to_inventory('apple')) print(add_to_inventory('banana')) ``` Also explain why this behavior occurs.

🟡 Medium Conceptual Junior level
1Times asked
May 2026Last seen
May 2026First seen

💡 Model Answer

The code will print:

['apple']
['apple', 'banana']

This happens because the default value for the parameter inventory is evaluated only once, when the function is defined. The list [] is created a single time and reused on every call where no explicit inventory argument is supplied. Each call appends to the same list, so the second call sees the item added by the first call.

To avoid this pitfall, use None as the default and create a new list inside the function:

python
def add_to_inventory(item, inventory=None):
    if inventory is None:
        inventory = []
    inventory.append(item)
    return inventory

Now each call starts with a fresh list unless a list is explicitly passed in.

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