You should not include the list creation in the argument declaration.
This is because the line that says def f(i, list1=[]):
actually creates a new list when it gets to the []
. This happens when the function is created.
Each time the function runs, it is re-using that same list object.
Think of it in terms of how the program runs, line by line. In effect the def
line ends up looking like this when it runs:
def f(i, list1=<a-new-list-that-I-just-created>):
And each time the function is called, the list1 default value is not a new list, but the list that was created when the function was defined.
I believe this is what you want, if you want to avoid this, is:
def f(i, list1=None):
if not list1:
list1=[]
list1.append(i)
return list1