Sobes.tech
Senior

What will the code with a mutable default argument in function arguments output?

sobes.tech AI

Answer from AI

In Python, if a mutable object (such as a list or dictionary) is used as a default value for a function argument, this object is created once when the function is defined and is used in all subsequent calls without creating a new one. As a result, modifications to this object inside the function are preserved between 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]
print(append_to_list(3))  # Outputs: [1, 2, 3]

Here, the list my_list is not recreated on each call but the same object is used, so elements accumulate. To avoid this, it is common to use None as the default value 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