Python Default Args: A Surprising Behavior

One small Python feature has surprised almost every developer at least once. Default function arguments. At first glance, this looks perfectly normal def add_item(item, items=[]):   items.append(item)   return items You call it once. add_item("A") → ['A'] You call it again expecting a fresh list. add_item("B") → ['A', 'B'] Wait… what? The list didn’t reset. This is where Python teaches an important lesson about how it really works. Default arguments are created only once when the function is defined, not every time the function runs. So that same list keeps living in memory. To beginners it feels like a bug. To experienced developers, it’s a reminder: Understanding how a language *behaves internally* is just as important as knowing its syntax. The fix is simple: def add_item(item, items=None):   if items is None:     items = []   items.append(item)   return items Small detail. Big insight. Python is full of these tiny behaviors that quietly reveal how the language actually works. And honestly, those moments of confusion are often the best teachers. What was the first Python behavior that made you stop and say... “Wait… why is it doing that?” #Python

I want to talk with you, still I am studying at Rayat bahra Professional University(Punjab). I am doing graduation in "Bsc(Data analytics)" . I want a roadmap of a data analytics course according to you to build a great future.. Thank you 🙏

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories