Default Argument Values in Python
The Issue with Mutable Default Arguments
You've encountered a common gotcha in Python: default argument values are evaluated only once at the point of function definition in the defining scope. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
Your Example
In this case, my_list is a list that's created when the function is defined, and the same list is used for all function calls.
Why This Happens
- Default argument values are evaluated once at the point of function definition.
- The default value for
my_listis a mutable object (a list). - Each time you call
add_item, you're appending to the same list object.
The Solution
To avoid this issue, you can use None as the default argument value and create the list inside the function:
Alternatively, you can also use a more concise version:
By doing this, you ensure that a new list is created for each function call, and you avoid the issue of the function "remembering" previous calls.