Python traps · Python
Python: this list grows by ITSELF?!PRO
A default list is made once, so every call shares it. The box=None fix.
# This list grows by ITSELF ?! — a default list is made ONCE, so every call shares it.
def add(item, box=[]):
box.append(item)
return box
print(add(1)) # [1]
print(add(2)) # [1, 2] ?!
print(add(3)) # [1, 2, 3] ?!
# Fix: default to None, make a new list inside
def add_fixed(item, box=None):
if box is None:
box = []
box.append(item)
return box
+ 4 more lines in the app (Pro)
Open code P4 in Pocket Compiler
Download the Pocket Compiler app — free
No app yet? Install it, then open the app and type the code P4 in Code Library.