Avoiding Surprises with Mutable Default Arguments in Python

Mutable default arguments in Python functions can lead to surprising and often unintended consequences. Consider this example:

def add_to_dataset(new_data, dataset=[]):
    dataset.append(new_data)
    return dataset


result1 = add_to_dataset(5)
print(f"After adding 5: {result1}")


result2 = add_to_dataset(10)
print(f"After adding 10: {result2}")
After adding 5: [5]
After adding 10: [5, 10]

The empty list [] default argument is created once at function definition, not each function call. This causes subsequent calls to modify the same list, leading to surprising results and potential data processing bugs.

To avoid this issue, use None as the default argument and create a new list inside the function:

def add_to_dataset(new_data, dataset=None):
    if dataset is None:
        dataset = []
    dataset.append(new_data)
    return dataset


result1 = add_to_dataset(5)
print(f"After adding 5: {result1}")


result2 = add_to_dataset(10)
print(f"After adding 10: {result2}")
After adding 5: [5]
After adding 10: [10]

This approach ensures that a new list is created for each function call unless explicitly provided.

By avoiding mutable defaults, you ensure that each function call starts with a clean slate, preventing unexpected side effects and making your code more predictable.

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran