Mutability Vs Immutability

Python 2 datamodel
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like numbers, strings and tuples ... are objects that can not be changed. An easy way to understand that is if you have a look at an objects ID.

Take List for example:

>>> b = [1, 2, 3, 4]
>>> id(b)
47490376L
>>> b[1] = 1
>>> b
[1, 1, 3, 4]
>>> id(b)
47490376L

Take Dictionary for example:

>>> aDict = {'host': 'earth', 'port': 80}
>>> id(aDict)
46236680L
>>> aDict['port'] = 90
>>> id(aDict)
46236680L

Take Integer for example:

>>> a = 1
>>> id(a)
31121592L
>>> a = 2
>>> id(a)
31121568L

Take Tuple for example:

>>> aTuple = (1, 2, 3, 4)
>>> aTuple[1] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Take String for example:

>>> aString = "For Example"
>>> aString[1] = 'U'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,066评论 0 23
  • PARAMETERIZE ARRAYS WITH TYPES In Scala, you can instanti...
    RxCode阅读 828评论 0 0
  • 浮动元素 浮动元素的特征其框可以左右移动(根据float属性值而定),直到它的外边缘碰到包含框或者另一个浮动元素的...
    cccccccc7355608阅读 278评论 0 0
  • 昨晚的读书分享会非常成功。 尽管昨天我是生理期的第一天,但是因为是总策划,我的心全在如何准备好这场分享会上,以至于...
    梅子Mey阅读 340评论 4 4
  • 一直都想尝试做一期歌单,把那些感动过你我的歌手、歌词甚至只是曲子写出来和你们分享,歌曲比较杂,糅合了不同时期的情绪...
    苏家小六阅读 1,619评论 18 17