Bugs

Mutable Default Arguments in Python: The Hidden Bug

Using a mutable object as a default argument is one of Python's most surprising gotchas. The default is evaluated once when the function is defined, not on every call.


❌ Buggy Function

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item('apple'))   # ['apple']
print(add_item('banana'))  # ['apple', 'banana'] — unexpected!

✅ Fixed with None Sentinel

def add_item(item, items=None):
    if items is None:
        items = []  # Fresh list on each call
    items.append(item)
    return items
💡

Pro tip: Never use a mutable object (list, dict, set) as a default argument. Use None and initialize inside the function body.

Paste this code into LearnCodeGuide

Detect Python vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Python Code →

Related Guides

Python None Type ErrorPython Global Variable AbuseDetect Python Bugs