Predict the output · Python
Mutable Default Arguments
Easy Predict the output Most askedSeen at Google, Dropbox, Instagram
What are the three lines of output?
What does this print?
def add(item, bucket=[]):
bucket.append(item)
return bucket
print(add(1))
print(add(2))
print(add(3, []))
[1] [2] [3]
[1] [1, 2] [3]
[1] [1, 2] [1, 2, 3]
[1] [1, 2] [3, 1, 2]
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
[1] [1, 2] [3]
The default list is created once, when def runs, and shared by every call that omits bucket — so the second call appends to the same list. Passing an explicit list avoids it.
The idiom: def add(item, bucket=None): bucket = [] if bucket is None else bucket.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium