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

More than 5 years have passed since last update.

【Python学習メモ】リストについて

Last updated at Posted at 2018-12-16

これは、Pythonの学習メモです。

リストを使う場合には、注意しないといけない例があります。

>>> a = [1,2,3]
>>> b = a
>>> print(a,b)
[1, 2, 3] [1, 2, 3]
>>> b[0] = 10
>>> print(a,b)
[10, 2, 3] [10, 2, 3]

リスト「b」で要素を変更する場合は、リスト「a」に該当する要素も同時に変わります。

先ず:

次に:

リストはミュータブルであるため、b[0] = 10で要素を更新しますと:

要素を変更しても、「a」で定義したリストとのオブジェクトそのものは変わりませんので、リスト「a」は前と同じ参照先へ参照します。つまり、「a」の値も[10, 2, 3]になっています。オブジェクトidで確認しますと、以下になります。

>>> a = [1,2,3]
>>> b = a
>>> print(a,b)
[1, 2, 3] [1, 2, 3]
>>> print(id(a),id(b))
4516968584 4516968584
>>> b[0] = 10
>>> print(a,b)
[10, 2, 3] [10, 2, 3]
>>> print(id(a),id(b))
4516968584 4516968584
1
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
1
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?