
40
2
章
Python
の基礎、
IPython
と
Jupyter Notebook
2.3.1.11
変更可能なオブジェクト、不変なオブジェクト
Python
ではリスト、ディクショナリ、
Numpy
の配列、またユーザ定義のオブジェクトのほとんどが
変更可能(
mutable
)です。これはそのオブジェクト内に格納された値やオブジェクトが変更可能である
ことを意味します。
In [43]: a_list = ['foo', 2, [4, 5]]
In [44]: a_list[2] = (3, 4)
In [45]: a_list
Out[45]: ['foo', 2, (3, 4)]
一方、文字列やタプルは変更不可能(
immutable
)です。
In [46]: a_tuple = (3, 5, (4, 5))
In [47]: a_tuple[1] = 'four'
------------------------------------------------------------------
---------
TypeError Traceback (most recent call last)
<ipython-input-47-b7966a9ae0f1> in <module>()
----> 1 a_tuple[1] = 'four'
TypeError: 'tuple' object does not support item assignment
注意してほしいのは、あるオブジェクトが変更可能だか