Sobes.tech
Junior — Middle

What behavior is expected if an empty list is set as the default value for an argument in a function?

sobes.tech AI

Answer from AI

If you set an empty list ([]) as the default value for a function argument in Python, this list will be created once when the function is defined and used in all subsequent calls without being recreated. This means that if you modify this list inside the function (for example, by adding elements), the changes will persist between function calls.

Example:

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

print(append_to_list(1))  # Outputs: [1]
print(append_to_list(2))  # Outputs: [1, 2], not [2]

To avoid this behavior, it is common 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 ensures that a new list is created each time the function is called.