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
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