0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

浅いコピーと深いコピー

Posted at

浅いコピーと深いコピーの違いでハマったので、メモを残す。

import copy
dic = {0:['a', 'b'], 1:['c', 'd']}
dic_copy = dic.copy()
dic_deepcopy = copy.deepcopy(dic)
print('-'*15 + 'before' + '-'*15)
print(f'dic:         {dic}')
print(f'dic_copy:    {dic_copy}')
print(f'dic_deepcopy:{dic_deepcopy}')
dic_copy[0].append('e')
dic_copy[1].remove('c')
dic_copy[3] = ['f']
dic_copy[3].append('g')
print('-'*15 + 'after' + '-'*15)
print(f'dic:         {dic}')
print(f'dic_copy:    {dic_copy}')
print(f'dic_deepcopy:{dic_deepcopy}')
---------------before---------------
dic:         {0: ['a', 'b'], 1: ['c', 'd']}
dic_copy:    {0: ['a', 'b'], 1: ['c', 'd']}
dic_deepcopy:{0: ['a', 'b'], 1: ['c', 'd']}
---------------after---------------
dic:         {0: ['a', 'b', 'e'], 1: ['d']}
dic_copy:    {0: ['a', 'b', 'e'], 1: ['d'], 3: ['f', 'g']}
dic_deepcopy:{0: ['a', 'b'], 1: ['c', 'd']}

結論
浅いコピー(.copy)出生成したオブジェクトへの編集はコピー元に影響を及ぼす。なぜなら参照オブジェクトのアドレス値が一緒だから。
しかし、深いコピー(copy.copy)には影響を及ぼさない。なぜなら参照オブジェクトもコピーを生成するから

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?