LoginSignup
7
3

More than 5 years have passed since last update.

pythonで配列のコピーを渡す方法

Last updated at Posted at 2019-02-15

備忘録です.

追記

コメントをいただきました.
深い構造の配列でこのタイプの渡し方をすると下層にある値は変化してしまうため,copy.deepcopy()という関数を使うべきだというコメントをいただきました.


関数に配列を渡すときに参照渡しになっていると困るときがあったので.
配列のあとに[:]をつけると値渡しになります.

def hoge(arr):
    arr[0] += 1

arr_ref = [0, 1]
arr_val = [0, 1]

hoge(arr_ref)
hoge(arr_val[:])

print(arr_ref)
print(arr_val)

出力結果

[1, 1]
[0, 1]

確かに2つ目の配列が値渡しになっています.

7
3
2

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
7
3