Sobes.tech
Junior — Middle

For what reasons is it not recommended to use mutable objects as default values for function parameters?

sobes.tech AI

Answer from AI

In Python, default parameter values for functions are evaluated once at the time of function definition, not each time the function is called. If a mutable object (like a list or dictionary) is used as a default value, then all calls to the function without an explicit argument will use the same object. This can lead to unexpected side effects, such as accumulating changes across calls.

Example of the problem:

def append_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list

print(append_to_list(1))  # [1]
print(append_to_list(2))  # [1, 2] — expected [2], but the list retains changes

The correct approach is to use None and create a new object inside the function:

def append_to_list(value, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(value)
    return my_list

Thus, each function call will work with a new list.

For what reasons is it not recommended to use mutable… - sobes.tech