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?
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
!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.