Beware of Mutable Default Arguments in Python – A Common Mistake Explained!

Understanding Mutable Default Arguments in Python  

The Issue with Mutable Default Arguments  

One common mistake in Python is using a **mutable default argument** like a list (`[]`). When a mutable object is used as a default parameter, it **persists across multiple function calls**, leading to unexpected behavior.  

How Default Arguments Work in Python 

In Python, **default argument values are evaluated only once at the time of function definition**. This means that if a mutable object (like a list or dictionary) is used as a default value, it will be **shared across multiple function calls** instead of creating a new one each time.  

Example 1: The Unexpected Behavior

Code:

```python

def add_item(item, cart=[]):  # cart is assigned a mutable default list

    cart.append(item)  # Appends the item to the same list

    return cart  # Returns the modified list


print(add_item("apple"))  # First call

print(add_item("banana"))  # Second call

print(add_item("orange"))  # Third call

```

for more details, see Beware of Mutable Default Arguments in Python – A Common Mistake Explained!


Post a Comment

Previous Post Next Post