2024년 9월 10일 화요일

Caution for the copying of python list or dictionary ( '=' is not what you think!)

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

자주 틀리거나 헷갈리는 맞춤법 구분

 (1) 되다/돼다 :

      '되'와 '돼'가 들어가는 부분을 '하'와 '해'로 바꾸어 본다. 쓰지 않는 말이되더라도 둘중에 어느쪽이 더 자연스럽게 들리는지를 생각해보면 된다. (예를 들어, 앞의 글에서 '한다' 와 '핸다'를 비교하면 '한다'가 자연스럽기 때문에 '된다'를 쓰면 된다.) 


(2) 결재/결제 : 

     '재판'이라고 할때의 '재'와 경제라고 할 때의 '제'를 떠올리면 된다. '결재'는 '재판'이라고 할때 처럼 일종의 판단을 하는 것이고, '결제'는 경제 활동의 일종이므로 '제'를 쓴다.  


(3) 깨닫게, 깨닳게, 깨달케 :

     "깨달음"의 동사는 "깨닫다" 이다. ("깨닳다", "깨달다" 라는 단어는 없음.) 단지, "ㄷ" 받침이 불규칙적으로 변하여 "ㅇ" 앞에서 "ㄹ" 로 발음되는 것이다. (때문에 "깨달음", "깨달아" 는 맞는 맞춤법) 따라서, "깨닫게"를 제외하곤 전부 틀린 맞춤법이다.