What does this print?
def add(item, bucket=[]):
bucket.append(item)
return bucket
add(1)
print(add(2))Options
- [2]
- [1, 2] (Correct option)
- TypeError
- [[1], [2]]
Answer
[1, 2]
Why
Python creates a default value only ONCE, when the def line runs, not on every call.
Here the default is one single list object. Every call that does not pass bucket reuses that same list: the first call adds 1, the second adds 2 to the same list, so it prints [1, 2].
Fix: use None as the default and create a new list inside the function.
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketRemember
Never use [], {} or set() as a default argument.