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 3 years have passed since last update.

変数にリストを代入したが元リストの演算影響を受けてしまう

Posted at

リストを代入したリストの値が元リストの演算影響を受けてしまう

元のリスト```old_list```を汚さずに処理をしたく思い、下のように別の変数```new_list```に代入した。 ```remove```による要素削除を```new_list```に施したところ、```old_list```の要素も消えていた...
test.py
old_list = [1, 2, 3]
new_list = old_list
new_list.remove(2)

print(old_list)
#[1, 3] 
print(new_list)
#[1, 3]

解決策

```copy()```を使い、値渡しをする
solution.py
old_list = [1, 2, 3]
new_list = old_list.copy() #値渡し
new_list.remove(2)

print(old_list)
#[1, 2, 3] 
print(new_list)
#[1, 3]
0
1
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
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?