y = x[:]
の代わりに使用しy = x
ます。両方をy = x
意味し、現在は同じオブジェクトを指しています。y
x
次の例を見てください。
>>> x=[1,2,3,4]
>>> y=x
>>> y is x
True # it means both y and x are just references to a same object [1,2,3,4], so changing either of y or x will affect [1,2,3,4]
>>> y=x[:] # this makes a copy of x and assigns that copy to y,
>>> y is x # y & x now point to different object, so changing one will not affect the other.
False
x がリストの場合、リストのリストは役に立ち[:]
ません:
>>> x= [[1,2],[4,5]]
>>> y=x[:] #it makes a shallow copy,i.e if the objects inside it are mutable then it just copies their reference to the y
>>> y is x
False # now though y and x are not same object but the object contained in them are same
>>> y[0].append(99)
>>> x
[[1, 2, 99], [4, 5]]
>>> y
[[1, 2, 99], [4, 5]]
>>> y[0] is x[0]
True #see both point to the same object
そのような場合、copy
モジュールのdeepcopy()
function を使用する必要があります。オブジェクトの浅くないコピーを作成します。