Course contentsShow
← Python
Lesson 239 of 1,0604. Data Structures MasteryFree lesson

Managing Mutable Default Arguments in Nested Structures

You will troubleshoot and resolve common bugs caused by mutable default arguments when passing complex data structures into reusable functions.

In this lesson, you will learn how to prevent unexpected data persistence bugs when using mutable objects as default arguments in your functions.

The Problem: Shared Memory

In Python, default arguments are evaluated only once—at the moment the function is defined, not every time it is called. When you use a mutable object like a list or a dict as a default value, that single object persists in memory across every single call to that function.

Consider this common mistake:

def add_item(item, storage=[]):
    storage.append(item)
    return storage

print(add_item("Apple"))  # ['Apple']
print(add_item("Banana")) # ['Apple', 'Banana'] - Wait, why is the first one here?

Because storage is created when the function is defined, every subsequent call appends to the same list. When you work with nested structures, such as a list of dictionaries, this bug can lead to data leaking between entirely unrelated operations.

The Solution: Using None as a Sentinel

To avoid this, we use None as a placeholder. Since None is immutable, it doesn't carry the risk of shared state. You then initialize the mutable structure inside the function body. This ensures that a brand-new object is created every time the function runs.

def add_item_safe(item, storage=None):
    if storage is None:
        storage = []
    storage.append(item)
    return storage

print(add_item_safe("Apple"))  # ['Apple']
print(add_item_safe("Banana")) # ['Banana'] - Correct!

This pattern is especially vital when dealing with complex nested structures. If you are building a function that accepts a list of dictionaries as a parameter, you must ensure that if no argument is provided, the function creates a fresh instance of that list rather than relying on a reference that might have been modified by a previous call. By using the None pattern, you effectively isolate your function’s memory from its previous executions, keeping your data structures predictable and bug-free.

Key Takeaway: Always use None as a default value for mutable arguments and initialize them inside the function body to ensure each call uses a fresh, independent instance.