The default argument trap
What does this print, and why? How would you fix it?
def add(item, bucket=[]):
bucket.append(item)
return bucket
print(add(1))
print(add(2))
Show hint
Default values are evaluated once, when the def line runs, not on every call.
Show solution
# Prints:
# [1]
# [1, 2]
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
The same list object is shared by every call that uses the default, so it keeps growing. Use None as the default and create a fresh list inside the function.
Want a problem like this every day? See today's problem and keep a streak going.