The Python Trap That Catches EVERY Beginner! #shorts
Video: The Python Trap That Catches EVERY Beginner! #shorts by Taught by Celeste AI - AI Coding Coach
Watch full page →The Python Trap That Catches EVERY Beginner!
In Python, using mutable default arguments like lists or dictionaries can lead to unexpected behavior because the default object is created once at function definition, not each time the function is called. This common pitfall causes the same list to be shared across multiple calls, accumulating values unintentionally.
Code
def add_item(item, items=[]):
# Appends item to the default list, which persists across calls
items.append(item)
return items
print(add_item(1)) # Output: [1]
print(add_item(2)) # Output: [1, 2] — unexpected accumulation!
# Correct approach: use None as default and create a new list each call
def add_item_fixed(item, items=None):
if items is None:
items = [] # Create a new list for each call
items.append(item)
return items
print(add_item_fixed(1)) # Output: [1]
print(add_item_fixed(2)) # Output: [2] — behaves as expected
Key Points
- Default mutable arguments are initialized once when the function is defined, not on each call.
- This causes the same mutable object (like a list) to be shared across calls, leading to unexpected side effects.
- Use None as the default value and create a new mutable object inside the function to avoid this trap.
- This pattern ensures each function call gets its own independent list or dictionary.
- Understanding this behavior is crucial for writing bug-free Python functions with mutable defaults.