Sobes.tech
Junior — Middle

Tell me about a common mistake you made in a previous project and how you fixed it.

sobes.tech AI

Answer from AI

In one of my projects, I encountered an error related to mutable objects in Python, specifically using a list as a default value in a function. Because of this, multiple calls to the function caused the list to accumulate elements, leading to unexpected behavior.

Example of the error:

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

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] — unexpectedly

I fixed this by replacing the default value with None and initializing the 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] — now correct

This way, I avoided side effects associated with mutable default values.