B4TTLESNAKE
B4TTLESNAKE

Reputation: 3

Variable inconsistency in Python?

I've run into a strange inconsistency. This is a simplified version of the problem:

func1={
    'flist':[12,13,14],
    'fnum':10
}

dlist=func1['flist']
dnum=func1['fnum']

dlist+=[16]
dnum+=1

print(func1)
print(dnum)

The output is:

{'flist': [12, 13, 14, 16], 'fnum': 10}

11

Why is that the changes to the variable dlist are carried over to flist in func1, but changes in dnum are not carried over to fnum in func1?

flist has changed, fnum has not.

Upvotes: 0

Views: 96

Answers (1)

fhorrobin
fhorrobin

Reputation: 362

This has to do with the mutability of the underlying objects. Since func1['flist'] refers to a list, when you do dlist=func1['flist'] you are actually getting a reference to the memory address of func1['flist'] and then when you add another value, you are modifying the same object in memory. This is because lists are mutable objects and referred to by reference.

On the other hand when you do dnum+=1, what is happening in memory is that 10+1=11 is being created as a new object in memory and then dnum is set to point to the new memory address. This has no effect on the memory address and therefore the value of func1['fnum']. This is the behaviour that happens for immutable types.

Upvotes: 1

Related Questions