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]Listの参照と別リストの生成

Last updated at Posted at 2025-05-25

1. この記事のポイント(結論)

多次元リスト(内包のリスト)を生成するには少なくとも以下の2つの方法があるがそれぞれ挙動が異なるので注意しなければならない

方法1
list_A = [[0]*2] * 2]
print(list_A)

# output >>> [[0, 0], [0, 0]]
方法2
list_B = [[0]*2 for _ in range(2)]
print(list_B)

# output >>> [[0, 0], [0, 0]]

ポイント

方法1 -> 最初に作成した[[0]*2]のリストを*2回分参照している
方法2 -> 最初に作成した[[0]*2]のリストと同じ内容の別のリストを作成している

2. それぞれの挙動の違い

それぞれ要素の値を変更した際に違いが発生する

  • 方法1 -> ある特定の要素に実行した変更が参照先にも反映さえる
  • 方法2 -> ある特定の要素に実行した変更は他のリストの要素には反映されえない
方法1
list_A = [[0]*2] * 2]
list_A[0][0] = 1
print(list_A)

# output >>> [[0, 1], [0, 1]]
方法2
list_B = [[0]*2 for _ in range(2)]
list_B[0][0] = 1
print(list_B)

# output >>> [[0, 1], [0, 0]]

方法1では、リストの中に内包されている2つのリストの両方の[0][0]の要素が1に更新されている。
これはリスト生成の際の方法が元のリストを参照する形になっているため、内包されいている1つ目のリストにだけ変更を加えたと思っても、そのリストを参照している2つ目のリストにも影響が及んでいる

方法2では、内包されいてる1つ目のリストをベースに、完全に別物のリストをもう一つ作り2つ目の内包リストとして管理しているので、1つ目のリストへの変更はもう1つのリストに影響しない。

実行例スクリーンショット

image.png

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