Why Your Python Functions Are Secretly Changing Data You Never Passed to Them
Your function looks right. The logic checks out. You've traced it three times on paper. But every time you call it, the output is wrong — and getting worse with each call.
You didn't pass broken data. You didn't modify anything. You didn't even sneeze in the wrong direction.
But something is changing. Quietly. Every single time.
This is the mutable default argument bug. And it's one of the most disorienting things Python will ever do to you.
The Bug That Doesn't Look Like a Bug
Here's the code. Read it slowly.
def add_item(item, cart=[]): cart.append(item) return cartr1 = add_item("laptop")r2 = add_item("mouse")r3 = add_item("headphones")print(r1) # ['laptop', 'mouse', 'headphones'] ← wait. WHAT.print(r2) # ['laptop', 'mouse', 'headphones']print(r3) # ['laptop', 'mouse', 'headphones']
You called add_item three separate times, stored each result separately, and printed them individually. Every single one shows the full accumulated list — even r1, which was returned after only the...
Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE