Why does ID of array element keeps on changing?
In [43]: x = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [44]: print id(x[0])
30836416
In [45]: print id(x[0])
31121344
In [46]: print id(x[0])
31471808
This is not the case when it is written in a python script
When written in python script we get the same ID
And also other observation is in the below figure
aCopy is the copy of the array a. id for the same element of both the arrays is printed twice. According to the output, id of all the array elements whether it may be of the same array or different (copy) is same except for the FIRST print. Why id of same element of two different arrays are same? Why one of the id when printed multiple times is different?
The id()
return value in CPython is based on the memory address of the argument.
When printing in a program there is nothing happening between the prints so it is more likely the same address gets reused for the x[0]
result, which is a newly created object each time. And it is garbage collected after printing.
In IPython on the other hand each user input is permanently stored in a history, so objects are created between the prints, which makes it more unlikely the x[0]
objects get placed at the same memory address.
When doing two prints in one go in IPython I get the same ID for both objects, but a different one for each time I do this:
In [28]: print id(x[0]); print id(x[0])
140000637403008
140000637403008
In [29]: print id(x[0]); print id(x[0])
140000637402608
140000637402608
In [30]: print id(x[0]); print id(x[0])
140000637402928
140000637402928
Of course this isn't guaranteed either.