Reputation: 11
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
Upvotes: 1
Views: 1179
Reputation: 308206
=
always creates a new reference, and never creates a new object.
What you're seeing is the difference between +=
and .append()
. Integers in Python are immutable, so when you try to change it you have no choice but to reference a different object - the 1
will always be 1
. On the other hand lists are mutable, so .append()
can change the single list object and add something new to the end of it.
Upvotes: 2