I illustrate my problem with a piece of code:
def foo(n, li = []):
if len(li) > n:
return li
li.append(str(len(li)))
foo(n, li)
return li
if __name__ == '__main__':
print(foo(2))
print(foo(5))
print(foo(2))
print(foo(2, []))
I have a recursive function with a default parameter li
. When I call the function without that parameter set, I expect it to take the default value, []
. So, for the third call I expect the same output as for the first call. Instead I get:
['0', '1', '2']
['0', '1', '2', '3', '4', '5']
['0', '1', '2', '3', '4', '5']
['0', '1', '2']
Why is the value of li
kept between calls to foo
?