0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python シャローコピーとディープコピーの違い

Last updated at Posted at 2025-01-19

Pythonでは、オブジェクトをコピーする際に「シャローコピー」と「ディープコピー」という2つの方法がある。

シャローコピー

  • コピーしたオブジェクトと元のオブジェクトは同じメモリを参照する
  • コピーしたオブジェクトの浅い層を更新しても、元のオブジェクトは変更されない
  • コピーしたオブジェクトの深い層を更新すると、元のオブジェクトが変更される
  • メモリ効率は良いのでパフォーマンスはいい
import copy

original = {"a": {"nested": 1}, "b": 2}
shallow_copy = copy.copy(original)

# シャローコピー後の変更
shallow_copy["a"]["nested"] = 99
shallow_copy["b"] = 999

print("Original:", original)  # {'a': {'nested': 99}, 'b': 2}
print("Shallow Copy:", shallow_copy)  # {'a': {'nested': 99}, 'b': 999}

ディープコピー

  • 元のオブジェクトと、コピーしたオブジェクトは独立している
import copy

original = {"a": {"nested": 1}, "b": 2}
deep_copy = copy.deepcopy(original)

# ディープコピー後の変更
deep_copy["a"]["nested"] = 99

print("Original:", original)  # {'a': {'nested': 1}, 'b': 2}
print("Deep Copy:", deep_copy)  # {'a': {'nested': 99}, 'b': 2}

まとめ

特徴 シャローコピー ディープコピー
ネスト部分の参照 共有する 独立する
影響範囲 ネストされた部分を変更すると影響する 完全に独立しているため影響しない
処理の深さ 表層的なコピー 再帰的に全てをコピー
パフォーマンス 高速 (ネストが少ない場合) 遅い (ネストが深い場合は時間がかかる)
0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?