I'm a bit confused about function variable scope, sometimes the function keeps track of its local variables so that if it's called again it recalls the previous values of the variables - and other times it doesn't keep track of the values.
In the following code, the function keeps track of the mylist
and appends to it at every call.
def test(mylist=[]):
mylist.append(1)
print (mylist)
test()
test()
test()
The output:
[1]
[1, 1]
[1, 1, 1]
While in the following code, x
is set to zero each time the function is called.
def test(x=0):
x+=1
print (x)
test()
test()
test()
The output:
1
1
1
What is the explanation of this behavior?
Also, is there a way to take a look at the current values of variables inside the functions from outside?
[Update]
After comments, I now understand why mylist
is updated, but what about x
in the second case? why is it not updated? is it because x
is immutable while mylist
is mutable?