0
a=np.array([[1,2],[4,5]])
b=a.T
print(a is b)
print(np.shares_memory(a,b))
for i in a:
    for j in I:
       print(i,j,id(j))
print('************')
for i in b:
    for j in I:
        print(i,j,id(j))

The output of the above code is
False
True
[1 2] 1 2027214431408
[1 2] 2 2027214431184
[4 5] 4 2027214431408
[4 5] 5 2027214431184
************
[1 4] 1 2027214431632
[1 4] 4 2027214431184
[2 5] 2 2027214431632
[2 5] 5 2027214431184

My question is why the location of alternate integer objects are the same in the above code. As python initializes different memory locations to each different objects

affan skm
  • 13
  • 4
  • `id` is no use when looking at array elements. Arrays store elements by value, not reference. Read numpy basic docs to answer your storage question. – hpaulj Jul 07 '21 at 14:31

1 Answers1

0
In [64]: a=np.array([[1,2],[4,5]])
    ...: b=a.T

The data value from __array_interface__ tells us (in some sense) where the data-buffer of the array is located. a and b has the same value, indicating that they share the buffer.

In [65]: a.__array_interface__
Out[65]: 
{'data': (74597280, False),
 'strides': None,
 'descr': [('', '<i8')],
 'typestr': '<i8',
 'shape': (2, 2),
 'version': 3}
In [66]: b.__array_interface__
Out[66]: 
{'data': (74597280, False),
 'strides': (8, 16),
 'descr': [('', '<i8')],
 'typestr': '<i8',
 'shape': (2, 2),
 'version': 3}

b is a view of a, using the same buffer, but with its own shape and strides.

In [67]: a.strides
Out[67]: (16, 8)
In [68]: b.strides
Out[68]: (8, 16)

Asking for the id of an indexed element tells us nothing about that data-buffer. It just identifies the object that was derived from the array - by value, not by reference. list stores elements by reference, arrays do not.

In [70]: type(a[0,1])
Out[70]: numpy.int64
hpaulj
  • 221,503
  • 14
  • 230
  • 353