Python Output Prediction Hard +35 XP
Mutable Default Argument
What happens when we call this twice?
PythonRead-only
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item("a"))
print(add_item("b"))What is the output?
Show answer and explanation
Answer: ["a"] then ["a", "b"]
Default mutable arguments persist between calls! The same list object is reused. Use None as default instead.
Hint: Default arguments are evaluated once.
What this challenge tests
Output Prediction in Python: functions, gotchas, mutable.