← Python
#1 most askedVery commonMediumData types & mutability

The mutable default argument trap

🏢 Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

Predict the output, explain why it happens, and show the fix.

🔮 Predict the output

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

add_item("apple")
print(add_item("pear"))

🎤 Answer it out loud, then check yourself

Say your answer as if the interviewer is listening (30–90 seconds). Then reveal what a strong answer covers and tick what you said.

    Try it · run and change it
    def add_item(item, basket=None):
        if basket is None:
            basket = []
        basket.append(item)
        return basket
    
    add_item("apple")
    print(add_item("pear"))
    
    Answer out loud first, then compare.
    Want to rehearse it?
    Answer this to the AI interviewer and get a verdict →