2017년 3월 29일 수요일

Python referencing( copying variables, objects)

In many language (at least, in Fortran), '=' makes a copy of a variable, so

a=1; b=a;  b=2

makes a=1 and b=2. Thus any change of the copy does not change the original.
This is the same for python, if the variable is a simple object.

However, in python, 'list1= list2' does not make two lists. Instead it refers the same reference object. Since, if a new value is assigned to the list, it may be okay.

a=[1,2,3]; b=a; b=[4,5,6]

makes a as [1,2,3] and b as [4,5,6] since the last  assignment 'b=[4,5,6]'
can be considered as a new assignment.

However, if we modify its elements,

a=[1,2,3]; b=a ; b[1]=7

makes both a and b as [1,7,3] (instead of a as [1,2,3], b as [1,7,3] )
since a and b were both refer the same object.

To obtain the originally desired effect, one can use

(1) b=a[:]  or b[:]=a[:]
(2) b=list(a)
(3) b=copy.copy(a)






댓글 없음:

댓글 쓰기