I'm searching for fast way to copy a object or list. Found following suggestions
b = a[:]
<-- fast
b = a.copy()
<-- slower
Yes, it worked but yet problem remains.
if I change the content of b
then the content of a` is also changed, why?
--- following is my trial code ---
>>> import numpy as np
>>> a = np.zeros([4,4])
>>> a
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> hex(id(a))
'0x16b21959a30'
>>> b = a
>>> hex(id(a)), hex(id(b))
'0x16b21959a30', '0x16b21959a30'
>>> c = a[:]
>>> hex(id(a)), hex(id(b)), hex(id(c))
('0x16b21959a30', '0x16b21959a30', '0x16b1fc54800')
Here, we found address of c
is different from others. (address of a
and b
is same)
So now try to change content of c
and verify content of a
.
>>> c[0][0]
0.0
>>> c[0][0] = 11
>>> c
array([[11., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> a
array([[11., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> b
array([[11., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
I changed only c[0][0]
, but I see a[0][0]
and b[0][0]
is also changed.
Why?