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