LoginSignup
0
1

More than 1 year has passed since last update.

リストと参照 Python競プロメモ⑤

Last updated at Posted at 2021-05-07
list_a = [1,2,3]
list_b = list_a
list_b[0] = "a"
print(list_a)
print(list_b)

上のコードを実行すると、結果は以下のようになる。

["a",2,3]
["a",2,3]

書き換えたのは、list_bの0番目の要素だけのはずだが、printしてみると明らかなように、list_aもまた0番目の要素が"a"となっている。これはリストが参照され、同じリストとして扱われるためである。

ここで、この解決策を記述しておく。
参照せずに、まったく同じリストを作成したいときはcopy()を用いることで可能となる。
そのコードを実際に記述すると

import copy
list_a = [1,2,3]
list_b = copy.copy(list_a)
list_b[0] = "a"
print(list_a)
print(list_b)

先ほどのコードと、copyの部分だけが異なっているが、このコードを実行すると、以下のようになる。

[1,2,3]
["a",2,3]

このように、list_bだけが書き換えられて、list_aはそのままのリストとして取り出すことに成功した。

0
1
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
1