Reallocating pointer memory in python

I am confused about python pointer handling. For example:

a=[3,4,5]
b=a
a[0]=10
print a

      

returns [10, 4, 5]

Above, it would be stated that b and a are pointers to the same place. The problem is that if we say:

a[0]='some other type'

      

b is now ['some other type', 4, 5]

This is not the behavior I would expect, since python had to reallocate memory at the pointer location due to the increase in the size of this type. What exactly is going on here?

+3


source to share


2 answers


  • Variables in Python are simply a reference to the memory location of the object being assigned.
  • Changes made to a mutable object do not create a new object

When you execute b = a

, you are actually asking b

to reference the location a

and not the actualobject

[3, 4, 5]



Further clarify:

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]

      

+4


source


Python has no pointers. Your code creates another variable b that becomes a reference to a, in other words, it just becomes a different way of referring to a. Everything you do with it is also done as they are both names for the same thing. For more information see python variables are pointers? ...



0


source







All Articles