Sobes.tech
Junior — Middle

Is it possible to set a list as the default value for a function parameter?

sobes.tech AI

Answer from AI

In Python, mutable objects (such as lists) should not be used as default parameter values for functions without caution, as this can lead to unexpected behavior because the default value is evaluated only once when the function is defined.

Example of the problem:

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

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] — the list persists between calls!

The correct way is to use None as the default value and create a new list inside the function:

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

print(add_item(1))  # [1]
print(add_item(2))  # [2]

Thus, technically, you can set a list as a default value, but it is not recommended to do so directly due to how Python handles mutable objects.

Is it possible to set a list as the default value for… - sobes.tech