1

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?

Ehab
  • 566
  • 6
  • 24
  • Functions don't track values from one call to the next. What's happening in the first one is a quirk of default arguments that is heavily recommended to avoid using unless you have a really good reason, as per @0x5453's link. – Kemp May 07 '21 at 12:24

1 Answers1

1

It's not mylist that's kept between invocations of the function, but rather the default value [], which is a single anonymous array that's assigned by reference to mylist each time.

Appending to mylist of course appends to the array that it refers to.

In the first case, x contains a reference to an array, and when you "add to x" you modify that array. In the second case, x simply contains a number 0, and when you "add to x", you change what x contains.

The key point is that the expression for the default parameter value is evaluated only once, and re-used between calls to the function.

Welcome to Python :-(

Martin Kealey
  • 546
  • 2
  • 11
  • So, why x is not updated in the second case? – Ehab May 07 '21 at 12:38
  • In the first case, x contains a reference to an array, and when you "add to x" you modify _that_ array. In the second case, x simply contains a number `0`, and when you "add to x", you change what x contains. – Martin Kealey May 07 '21 at 13:17