Monday, August 30, 2010

"Pointers" in Python

Firstly, I want you to understand that, the term "pointers" used here, is a
misnomer.

In Python, there is no particular data type called a pointer; as in C. Even so,
some operations that we can perform in Python, are very similar to the
structure of a pointer.

Ok, I've been bragging till now about pointers, let me tell you what it is.

Visualize that, a new data type that you create has to be stored in a memory location in the hard disk. This memory location, has an address.
In C, a pointer can be defined whose value is such a memory 
address. Any valid operation done on this pointer, will be 
automatically reflected in the data present in that address. 

Now lets see, where this happens in Python.

Lets create a list and  copy it.
>>> a = [1,2,3]
>>>b = a 
Now lets change an element of a.
>>>a[1] = 10
>>>a
[1,10,3]
Now check the value of b.
>>>b
[1,10,3]

We can see that b has also changed. How did this happen? 

When the list a was created, it was stored in a memory location say 2000, 
and the value 2000  was put in a. When a was assigned to b, it meant that
now b too contain the value 2000. Then we changed the second element of
a, i.e, the data in the address 2000. Therefore, now if we print the value of  
a or b, we will only get the changed list, since both a and b are actually
"pointers" to the memory address 2000.

N. B.
1. Be careful with list assignments!
2. What I discussed above, does not hold for slicing operations on a list.
   When any list is sliced, first a copy of it is created in another memory
    location, and then the operations are performed. Thus, the changes won't
    reflect back in the original list.  

No comments:

Post a Comment