So I have been using python for quite a while without knowing some of the nuances. Recently I discovered that when assigning an old variable to a new variable, what being assigned is just a reference to the old variable instead of the actual value of it. So I did a little test:
def change_number(b):
a=b
a+=1
return a, b
b=1
print(change_number(b))
def change_list(b):
a=b
a.append("x")
return a,b
b=["a","b"]
print(change_list(b))
The results are:
(2, 1)
(['a', 'b', 'x'], ['a', 'b', 'x'])
It seems that when dealing with numbers, python are treating the variables separately. Whereas when dealing with lists, a single instance beneath the two references is updated regardless of which one the operation is called upon.
I am thinking that this difference might be related to the types of objects python is dealing with, but it seems that it may also have something to do with the operation being done. I have read several related answers with respect to specific problems, but I would really like to know the general rule of python dealing with new variable assignments related to existing ones under difference circumstances. Cheers
intobjects happen to be immutable, so you cant change them, but the semantics of assignment are exactly the same. I second the call to read: nedbatchelder.com/text/names.htmlchange_listyou dida = a + [42]you would see the same effect.+on lists creates a new list. (+=on lists does not, though. The inequivalence ofx += yandx = x + yfor mutable types is a frequent source of confusion for new Python programmers.)