Sobes.tech
Junior — Middle

Why is it not recommended to set an empty list as the default value for a function parameter?

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 an empty list is set as the default value, this list will be shared across all calls to the function, which can lead to unexpected side effects.

For example:

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] — the list persists between calls

To avoid this, it is better to use None as the default value and create a new list 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

This way, each call to the function will work with a new list.