Why Did One Value Change But The Second Value Did Not?
Solution 1:
The two examples are not equivalent.
By doing b = a
you are telling b
to point to the same list that a
points to. If you change the list through a
it will be changed even if introspected through b
. There is only ever one list in memory.
In the second example you are doing d = c
which tells d
to point to the same integer that c
does, but then you are telling c
to point to another integer. d
does not know about it, and it is still pointing to the same integer that c
used to point to.
The equivalent example using lists to your second example will be
a = [1, 2]
b = a
a = []
print(a)
# []
print(b)
# [1, 2]
Check these visualizations:
Solution 2:
The answer provided by @DeepSpace is a good explanation.
If you want to check if two variables are pointing to the same memory location you can use is
operator and to print them use id
.
>>>a=[1,2]>>>b=a>>>a is b
True
>>>id(a),id(b)
(2865413182600, 2865413182600)
>>>a.append(2)>>>a,b,id(a),id(b)
([1,2,2],[1,2,2],2865413182600, 2865413182600)
>>>a=[1,2]>>>b=[1,2]>>>a is b
False
Solution 3:
It's all about if the object you assign is mutable
or immutable
.
Simply put - mutable objects can be changed after they are created, immutable objects can't.
Considering you have a variable a
that is assigned to an object, when you point a new variable to the a
variable, there are two possibilities:
- If an object is
mutable
-> you will just point to the same object with your new variable - If an object is
immutable
-> you will assign a new object to your new variable.
Your first case:
- First you create a list
a
, which is a mutable object - Then you point with a second variable
b
to the same list object. - When you change value, you just change a mutable object, to which both variables are pointing.
In second case:
- First you assign a variable
c
to an immutableint=4
object. - Then you assign it to the second variable
d
. - And what happens next, is that you assign a new immutable
int=8
object to the variablec
.
There is plenty of articles about what does it mean that an object is mutable, for example: https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
Post a Comment for "Why Did One Value Change But The Second Value Did Not?"