>>> x = 10
>>> y = x
>>> y = 100
>>> y # Changes on y will not be transferred to x
100
>>> x
10
>>> x2 = 'hello'
>>> y2 = x2
>>> y2 = 'world' # Changes on y2 will not be transferred to x2
>>> y2
'world'
>>> x2
'hello'
>>> a = [1, 2]
>>> b = a
>>> b.append(3) # Changes on b will be transferred to a
>>> b
[1, 2, 3]
>>> a
[1, 2, 3]
>>> x1 = {}
>>> y1 = x1
>>> y1['h'] = 'hhh' # Changes on y1 will be transferred to x1
>>> y1
{'h': 'hhh'}
>>> x1
{'h': 'hhh'}
Question> In which cases, the value of the assigned variables will affect the value
of original variables?
Python version: Python 3.1.2
You should consider that all variables in python are indeed pointers to objects.
Case 1
When you write
the variable
xis a pointer to a number object with value10.the variable
yis a pointer to the same object currently pointed byx.now the variable
yis instead pointing to another number object with value100. This clearly has no effect on the object thatxis pointing to.Case 2
When you write
xis pointing to an array object that contains two pointers to number objects with value1and2.yis now pointing to the same array asxthis doesn’t affect the variable
y(this is the key point!), but alter the object it is pointing to (the array) by adding another element. Becausexis also pointing to the same object the change will be visible fromxtoo.