Friday, April 13, 2012

Copy by Value Copy by Pointer


In Python, variables are treated like objects. In fact, data structures are classes and a specific data structure variable is an object of that class. Consider lists in Python. When you create a list variable, it is treated like an object of a class. The contents of the variable are not a set of values rather it is a pointer to the memory spaces that contain those values.
Therefore, when the variable is copied or assigned to another variable, the pointer is copied. The assignment will not duplicate values in the memory but it will duplicate the pointer and finally, there will two pointers pointing to the same memory spaces. As a result, if the contents are changed using the second variable, the contents for the first variable also get changed.

For example
>>> a=[23,45,66]
>>> b=a
>>> b[0]=90
>>> a
[90, 45, 66]
>>>

This is called copy by pointer.

Another way to explain it is this. For example, I have a document containing some text. After opening the document with MS Word, I can create multiple windows and all will show the content of the document. These are all pointers to the same content. If I change content in one of these, contents in the rest will be changed too.

Now if the contents are selected using ctrl+a and pasted to a new file in Notepad, Wordpad or even MS Word using ctrl+v, then the contents are duplicated instead of pointer. Now there will be two pointers pointing to different memory spaces. Changing contents using one will not affect other.

This is called copy by value. To copy the contents of a list, use the instruction, b=a[:] instead of b=a.


No comments: