Skip to main content

8.13) Copying And Referencing


An assignment with the = symbol, creates a reference to an object. The following will make the variable L reference the list [1,2,3]:

>>> L=[1,2,3]

If you assign a variable to another, you are in fact just creating another reference to the same object. The following will make the variable M reference the same list as L, the list [1,2,3]:

>>> M=L
>>> print M
[1,2,3]

Since mutable objects can be modified, any change to a list will affect all its references:

>>> L[1]='two'
>>> print M
[1, 'two', 3]
>>> M[2]='three'
>>> print L
[1, 'two', 'three']

See it in action with the following animation.

[advanced_iframe securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc" src="http://pythontutor.com/iframe-embed.html#code=%23+Copying+and+referencing%0A%0AL%3D%5B1,2,3%5D%0AM%3DL%0Aprint+M%0A%0AL%5B1%5D%3D%22two%22%0Aprint+M%0AM%5B2%5D%3D%22three%22%0Aprint+L&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2&curInstr=0"]