I am confused by python's handling of pointers. For example:
a=[3,4,5]
b=a
a[0]=10
print a
returns [10, 4, 5]
The above would indicate that b and a are pointers to the same location. The issue is what if we say:
a[0]='some other type'
b now equals ['some other type', 4, 5]
This is not the behavior I would expect as python would have to reallocate the memory at the pointer location due to the increase in the size of the type. What exactly is going on here?
2 Answers 2
- Variables in Python are just reference to memory location of the object being assigned.
- Changes made to mutable object does not create a new object
When you do b = a you are actually asking b to refer to location of a and not to the actual object [3, 4, 5]
To explain further:
In [1]: a = [1, 2]
In [2]: b = a # b & a point to same list object [1, 2]
In [3]: b[0] = 9 # As list is mutable the original list is altered & since a is referring to the same list location, now a also changes
In [4]: print a
[9, 2]
In [5]: print b
[9, 2]
Comments
Python does not have pointers. Your code creates another variable b, which becomes a reference to a, in other words, it simply becomes another way of referring to a. Anything you do to a is also done to be, since they are both names for the same thing. For more information, see python variables are pointers?.
b=a, so bothaandbare referring to same memory location?...whatever change you do usingawill be the same inb..