a = [ 1, 2 ]
b = a
a.append(3)
print(b) # shows [ 1 2 3 ] which means b changed
c = 4
d = c
c = 8
print(d) # shows 4 which means d did not change
Why
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
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:
mutable
-> you will just point to the same object with your new variableimmutable
-> you will assign a new object to your new variable.Your first case:
a
, which is a mutable objectb
to the same list object. In second case:
c
to an immutable int=4
object.d
.int=8
object to the variable c
. 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
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:
Your first example
Your second example
My example