I am writing this to expand my understanding of how pointers and memory-addressing work in python.
Python being a high level language, I have learned that the memory management is taken care of by python.
I have also learned that the pointers can be identified with id() object.
Assume I have two variables a and b, and these two variables can be swapped with the below command:
a,b=b,a
The change in identity of these variables can be found using the below methods.
>>> a=2
>>> b=3
>>> id(a)
140732857872688
>>> id(b)
140732857872720
>>> a,b=b,a
>>> a
3
>>> b
2
>>> id(a)
140732857872720
>>> id(b)
140732857872688
As you can see the ids are swapped (as expected) , and in the other words we can say the idsassigned to variable are swapped. How is this happening in python?
And in one more example,
>>> i=0
>>> id(i)
140732857872624
>>> i+=1
>>> id(i)
140732857872656
When i is incremented by 1 , how is a new variable( I am calling it new because the identity is changing) with the same name created under the hood?
I am adding one more example also to further expand my question!
Operation 1:
>>> i,j=0,0
>>> id(i)
140732857872624
>>> id(j)
140732857872624
>>> i,j = i+1,i+1
>>> i
1
>>> j
1
>>> id(i)
140732857872656
>>> id(j)
140732857872656
Operation 2:
>>> i,j=0,0
>>> i=i+1
>>> j=i+1
>>> i
1
>>> j
2
>>> id(i)
140732857872656
>>> id(j)
140732857872688
Of course operation 1 and operation 2 are different. How do both of these operations occur at a low level.
And once there is no more use for an already assigned pointer, how will it get reused ? if a memory-address can not be reused in a given program and new memory-address has to be given for each new operation(in the same program) , is it the reason behind memory overflow when recursion with a high depth is used?
I hope I have made my questions clear.
If my understanding is wrong anywhere , please correct me. Coming from Mechanical Engineering background, although I have been programming for quite some time , this thing is really confusing to me.
Regards