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
def add(item, bag=[]):
bag.append(item)
return bag
print(add(1))
print(add(2))def add(item, bag=None):
if bag is None:
bag = []
bag.append(item)
return bag

![Animated sliding window over the array [2, 1, 5, 1, 3, 2]: a three-number window adds the new number and subtracts the old one, showing sums 8, 7, 9 and 6 and a maximum of 9.](https://i.ytimg.com/vi/NM5paB6_7wg/maxresdefault.jpg)
![Animated JavaScript comparisons: 0 == "0" is true, 0 == [] is true and "0" == [] is false, then a conversion lane turns [] into an empty string and then 0, ending on ===.](https://i.ytimg.com/vi/aXBolMH19gs/maxresdefault.jpg)