Sobes.tech
Junior — Middle

How to implement a function in Python with a default argument that can be modified inside the function?

sobes.tech AI

Answer from AI

In Python, default arguments are initialized once when the function is defined, so modifying a mutable object (like a list) inside the function can lead to unintended effects.

To avoid this, it is common to use None as the default value and create a new object inside the function if the argument was not provided:


def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

# Usage example
print(add_item(1))  # [1]
print(add_item(2))  # [2], not [1, 2]

This approach allows you to modify the argument inside the function without risking affecting the default value between calls.