Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pointer memory reallocation

Tags:

python

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?

like image 511
Joesh Avatar asked Dec 30 '25 22:12

Joesh


1 Answers

  1. Variables in Python are just reference to memory location of the object being assigned.
  2. 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]
like image 178
geetha ar Avatar answered Jan 01 '26 12:01

geetha ar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!