1

My list:

a=[1,2,3,4,5]

b=a[:]

id(a)
>>2181314756864

id(b)
>>2181314855232 (different as slicing creates a new object)

id(a[0])
>>140734633334432

id(b[0])
>>140734633334432 (same)

b[0]=-1

b
>>[-1,2,3,4,5]

a
>>[1,2,3,4,5]  --perfectly fine

But in case of numpy:

import numpy as np

l=np.array([1,2,3,4,5])

p=l[:]

id(l)
>>2181315005136

id(p)
>>2181315019840 (different as it creates a new object, which is fine)

id(l[0])

>>2181314995440

id(p[0])
>>2181314995952 (different)

But:

p[0]=-1

p
>>array([-1,2,3,4,5])

l

>>array([-1,2,3,4,5])

Even though the memory addresses of first elements of numpy arrays are different, l is also being updated. Can anyone explain the concept behind this?

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    Does this answer your question? [What is the difference between slicing in numpy arrays and slicing a list in Python?](https://stackoverflow.com/questions/54389884/what-is-the-difference-between-slicing-in-numpy-arrays-and-slicing-a-list-in-pyt) – ThePyGuy May 17 '21 at 12:10
  • Thw question is similiar. But I wanted to know the reason of this behavior even though the memory addresses of elements of numpy arrays are different – Vivek Vankadaru May 17 '21 at 12:17
  • I understood the confusion. Let me reframe the question. As per documentation, or per the thread you have posted, the sliced array is still referenced to original array. But as per my example, the addresses of same elements in 2 different numpy arrays are different. so editing one array should change the original array. But the original array is also being changed. Why? – Vivek Vankadaru May 17 '21 at 12:23
  • When you do `p[0]` you get array scalar as described in https://numpy.org/doc/stable/reference/arrays.html. This is a whole new Python object, that takes its value from the array. It's not a reference as in the list case. So `id` tells us nothing. `p[0]=-1` also acts by value, not by reference as in the list case. – hpaulj May 17 '21 at 16:09

1 Answers1

0

Talking about id as a memory address is a bit of a red herring. Yes, in CPython, it happens to be a memory address, but the address of what? Not, as it happens, the actual numeric data, but the Python object that describes the numeric data!

Slicing in numpy creates a new Python object (hence a different id), but the new object shares the storage for the actual array with the old one.

If id(A) == id(B), then, for example, A.shape could not possibly be different from B.shape!

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
  • I keep telling people to read the numpy basics, but then realized that I can't find documentation that gives a clear picture of how arrays are stored. The closest I can find is the start of https://numpy.org/doc/stable/reference/arrays.html – hpaulj May 17 '21 at 16:19