LoginSignup
0
0

More than 3 years have passed since last update.

Pythonの浅いコピー深いコピーを軽く整理

Last updated at Posted at 2020-06-21

浅いコピー、深いコピーについて

>>> import copy
>>> l1 = [1, [2, 3]]

>>> l2 = l1
# 浅いコピー
>>> l3 = copy.copy(l1)
# 深いコピー
>>> l4 = copy.deepcopy(l1)

# l1とl2は同じ
>>> l1 is l2
True
>>> l3 is l1
False

# l1[1]とl3[1]は同じ(浅いコピーなので)
>>> l1[1] is l3[1]
True
>>> l1[1] is l4[1]
False

>>> l1.append(4)
>>> l1[1].append(4)
>>> l2
[1, [2, 3, 4], 4]
>>> l3
[1, [2, 3, 4]]
>>> l4
[1, [2, 3]]

関数の引数、デフォルト引数について

Pythonの関数は参照を渡しているので可変型を渡す時は注意しましょう。
また、デフォルト値に可変型を使う場合も注意しましょう。・・・怖いですね。

>>> def f(a, b=[]):
...   a.append(0)
...   b.append(0)
...   return a, b
...
>>> x = [1, 2]
>>> f(x)
([1, 2, 0], [0])
# pythonでは引数の参照がコピーされるので引数の内容を書き換えれる
>>> x
[1, 2, 0]
# デフォルト引数に可変型を使用するとデフォルト値を変更出来てしまう
>>> f(x)
([1, 2, 0, 0], [0, 0])

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