2

I am trying to understand why elements with different value have the same id. Could someone explain me what is going with respect to memory management in NumPy. Example below

import numpy as np
x=np.array([1,2,3,4])
print([id(a) for a in x])
[140718968034552, 140719258631960, 140718968034552, 140719258631960]

Here, first and the third element has the same id(140718968034552) though they hold different numerical values. Same as for second and fourth elements.

  • 3
    Don't pay attention to these `id` values. They aren't meaningful. Read my answer here https://stackoverflow.com/a/63873120/901925 esp. `[14]` – hpaulj Sep 14 '20 at 20:54
  • Does this answer your question? [What is the id( ) function used for?](https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for) – Random Davis Sep 14 '20 at 20:56
  • @Marios. How is that even remotely related to the question? – Mad Physicist Sep 14 '20 at 21:04
  • @Hpaulj, read the link. I understand -5 to 256 integers get static id due to memory optimization. But My question is, first and third integer objects are different (as holding different value), then why they have same id. – Masrul Huda Parvez Sep 14 '20 at 23:09
  • Look at the `type` of `a`. It isn't `int`. – hpaulj Sep 14 '20 at 23:37

1 Answers1

3
In [54]: x=np.array([1,2,3,4])
In [55]: [type(a) for a in x]
Out[55]: [numpy.int64, numpy.int64, numpy.int64, numpy.int64]
In [56]: [id(a) for a in x]
Out[56]: [140147220886728, 140147220887808, 140147220886728, 140147220887808]

The id of small integers is unique, but that's not what the array contains:

In [57]: [type(a) for a in x.tolist()]
Out[57]: [int, int, int, int]
In [58]: [id(a) for a in x.tolist()]
Out[58]: [10914496, 10914528, 10914560, 10914592]
In [59]: id(2)
Out[59]: 10914528

Another way to get the int objects:

In [60]: [id(a.item()) for a in x]
Out[60]: [10914496, 10914528, 10914560, 10914592]

edit

If I assign the elements of x to a tuple of variables, the id are not reused. id(x0) is still in use, so id(x2) cannot take it. The alteration in Out[56] is just an artifact of memory reuse by the interpreter.

In [73]: x0,x1,x2,x3 = x
In [74]: id(x0),id(x1),id(x2),id(x3)
Out[74]: (140146931335720, 140146931335504, 140146931335600, 140146931335576)
In [75]: type(x0)
Out[75]: numpy.int64
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks for the elaborate answer. Looks like numpy creates np.array in such way, concate( np.int64([all odd index]), np.int64([all even indices])). I checked with a larger array, I found that all odd and all even indices have the same object id. – Masrul Huda Parvez Sep 15 '20 at 03:24
  • That alternation is, I think, just an artifact of asking for values one after the other without hanging to any of them. It's just a memory reuse step, done by python, not `numpy`. In my earlier answer it took pains to avoid this reuse of ids: `x, y = arr[10], arr[10]; id(x), id(y)`. – hpaulj Sep 15 '20 at 04:34