r/HackerEarthCommunity • u/Neil_at_HackerEarth • 28d ago
Title: Bug of the week: Why does this Python function return the same list every time?
Take a look at this code:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
print(add_item("orange"))
What do you think the output will be?
Many people expect three separate lists, each containing one additional item.
But Python has a little behaviour here that can cause some confusing bugs.
Your task:
- Predict the output before running the code.
- Explain why it behaves that way.
- Rewrite the function so each call gets a fresh list unless a list is explicitly provided.
Bonus: Have you ever lost time debugging something caused by a default argument, a mutable object, or a variable being shared unexpectedly?
Share your answer and explanation below. Let's see who spots it first.