I found there is a surprising behavior of '=' in python!!
a = np.array([1,2,3]);b=a;b[0]=0;print(a,b)
[0 2 3] [0 2 3]
* When one use '=' in python , it usually mean to copy the values of the right hand side variable to the left hand side variable, i.e. assignment.
* However, in python, if the variable is a list or dictionary, '=' has different meaning.
The operation depends on the variable.
(1) If it is a default simple data type like, it creates different copy.
b=a : a and b are unrelated except they have the same values.
(2) If it is a compound object like list, dictionary, or complex object,
'=' means assign alternative name.
b=a : a and b directs the same adress and shares the values.
In other words, a and b are linked.
Thus, any change in a or b affacts the other.
To avoid this, one can copy the compound object. However, there is two different copies.
(1) Shallow copies : if the object is just a list or shallow, one can use
b = a[:] or b = a.copy()
This creates a shallow copy of a and changes in a or b does not affect the other
if the object is shallow(only one index).
However, if it is more complex object like list of lists, in fact they share memory.
Any change in deeper level of a or b affects the other.
(2) Deep copies : to make a completely decoupled copy of compound object.
one have to make a deep copy using 'copy' module.
import copy
b = copy.deepcopy(a)
REF: https://medium.com/@thawsitt/assignment-vs-shallow-copy-vs-deep-copy-in-python-f70c2f0ebd86
댓글 없음:
댓글 쓰기