Middle
Explain the behavior of a function with a mutable default argument. What will the prints output?
sobes.tech AI
Answer from AI
Mutable default arguments in Python (such as lists or dictionaries) are initialized only once when the function is defined, not each time the function is called. This means that if you modify such an argument inside the function, subsequent calls will use the already modified object, not a new one.
Example:
def func(a, my_list=[]):
my_list.append(a)
print(my_list)
func(1) # Outputs: [1]
func(2) # Outputs: [1, 2]
func(3) # Outputs: [1, 2, 3]
Here, my_list retains changes between calls, which often leads to errors.
To avoid this, it is common to use None as the default value and create a new object inside the function:
def func(a, my_list=None):
if my_list is None:
my_list = []
my_list.append(a)
print(my_list)
Now, a new list is created on each call.