Home

Default mutable arguments

def x(y=[]):
    return y

print(x())
# >> []

x().append(10)
print(x())
# >> [10]

In this part:

This behavior occurs because:

def my_function(default_list = None):
    if default_list == None:
        default_list = []
    return default_list

print(my_function())
# >> []

my_function().append(8)
print(my_function())
# >> []

This approach ensures that each call to my_function() gets a fresh, empty list, avoiding the issues seen in the first part.

my_function().append(8)
my_function().append(8)
print(my_function())
# >> []

Step-by-step explanation

my_function().append(8)
 # >> [] 

Step-by-step explanation

Key points

Why this behavior is correct

This behavior demonstrates the proper handling of mutable default arguments.By using None as the default argument and creating a new list inside the function when needed, we ensure that:

  1. Each call to the function gets its own fresh list.
  2. There’s no shared state between different calls to the function.
  3. Modifications to the returned list in one call don’t affect the lists returned by future calls.

This pattern avoids the common pitfall associated with mutable default arguments and provides more predictable and safer behavior in Python functions.

Tags: Python, Funtion Default Arguments