Sobes.tech
Middle

Why can't mutable types be used as default values for function arguments?

sobes.tech AI

Answer from AI

Mutable data types (lists, dictionaries, sets, etc.) in Python are created once when the function is defined. On subsequent calls, if the argument is not explicitly passed, the same object reference created during the first call is used.

This leads to changes made to this object in one call persisting and affecting subsequent calls, which can be unexpected and cause hard-to-debug errors.

# Example of incorrect usage
def add_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list

print(add_to_list(1))  # Output: [1]
print(add_to_list(2))  # Expected: [2], but outputs: [1, 2] - problem due to mutable default argument

The correct approach is to use an immutable default value, such as None, and then create a new mutable object inside the function if the argument was not provided.

# Example of correct usage
def add_to_list_correct(value, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(value)
    return my_list

print(add_to_list_correct(1))  # Output: [1]
print(add_to_list_correct(2))  # Output: [2] - each call creates a new list

Comparison of behavior:

Scenario Mutable default value Immutable default value (None)
First function call Object is created Object (None) is created, then a new list
Subsequent calls Existing object is used New object (None) is created, then a new list
Object modification Changes are saved Changes do not affect subsequent calls