Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I made this function:
def test(num,v=[]):
v.append(num)
if num == 10:
return v
return test(num+1,v)
When I use it, the result of previous calls seems to still be there:
>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10]
>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10]
>>> test(3)
[3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10]
If I use just v
in the function declaration as opposed to v=[]
, it seems to work.
What am I missing? I want the function to be fresh each time I run it. I use Python 2.7.3.