4

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

IPython Screenshot

This is not the case when it is written in a python script When written in python script we get the same ID Python script screenshot

And also other observation is in the below figure Behaviour when printed ID of copy of the array for the same element

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?

Sanober Sayyed
  • 172
  • 1
  • 10

2 Answers2

1

id(x[0]) is the pointer of the object created by x.__getitem__(0). That object is created by numpy code each time you call this, and apart possible caching, will be different. It is not the id of the bytes in x.data that represent the first array element. array storage is by value. List storage is by reference, ie.e. pointer.

This is a duplicate question, but finding the right SO link may be difficult.

From python docs for id

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

If you get repeats of id, check for non-overlapping lifetimes.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
1

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.

BlackJack
  • 4,476
  • 1
  • 20
  • 25