0

So Im trying get mutability a bit better into my brain and I saw quite a lot of experienced people struggle sometimes.

I made this little test code here:

x = 1
def test():
    x = 2
test()
print(x) #1


x = 1
def test():
    global x
    x = 2
test()
print(x) #2


x = [1]
def test():
    x = [2]
test()
print(x) #[1]


x = [1]
def test():
    global x
    x = [2]
test()
print(x) # [2]


x = [1]
def test():
    x[0] = 2
test()
print(x) #[2]

Everything is clear to me except what the difference between the last and second last could be. What exactly is the rule to this. I noticed that it is possible to change the value of the object but not the object type itself or did I understand this wrong?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
itsolidude
  • 1,119
  • 3
  • 11
  • 22

1 Answers1

1
# case 1
x = 1
def test():
    x = 2
test()
print(x) #1

# case 2
x = 1
def test():
    global x
    x = 2
test()
print(x) #2

In case 1, the variable x inside test is locally scoped hence changing its values does not change the value of x declared outside test and hence doesn't mutate x which is declared outside test.

In case 2, the variable x inside test is globally scoped hence changing its values does change the value of x declared outside test and hence does mutate x outside test.


# case 3
x = [1]
def test():
    global x
    x = [2]
test()
print(x) # [2]

# case 4
x = [1]
def test():
    x[0] = 2
test()
print(x) #[2]

In case 3, the list x inside test is globally scoped at holds a reference to the list outside test, but when you assign a new list to x, a new reference is created to this list [2] and mutating this new list doesn't mutates the value in the list declared outside test.

In case 4, the list x inside the test method holds reference to the same instance of list which is declared outside the function test, when you call x[0] you are not changing the reference to the list but rather you are assigning the value 2 to index 0 inside the same list, which mutates the outside list.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53