Skip to content
Python Trap

Python Trap

Python Mutable Default Argument Trap: Why def f(x=[]) Shares One List

· Python mutable default argument trap | add(2) kya print karega?

Python creates a mutable default argument once, when the function is defined, not on every call. That is why def add(item, bag=[]) returns [1, 2] on the second call. The fix: default to None and build a new list inside.

The code

bug
def add(item, bag=[]):
    bag.append(item)
    return bag

print(add(1))
print(add(2))
fix
def add(item, bag=None):
    if bag is None:
        bag = []
    bag.append(item)
    return bag
Daily TrapOne more trap, every dayA short JavaScript or Python output puzzle each day. Guess, see why, keep your streak.