Why tuple is not mutable in Python? [duplicate]

怎甘沉沦 提交于 2019-12-04 13:18:28

问题


Possible Duplicate:
Why are python strings and tuples are made immutable?

What lower-level design makes tuple not mutable in Python? Why this feature is useful?


回答1:


A few reasons:

  • Mutable objects like lists cannot be used as dictionary keys or set members in Python, since they are not hashable. If lists were given __hash__ methods based on their contents, the values returned could change as the contents change, which violates the contract for hash values.
  • If Python only had mutable sequences, constructors which accepted sequences would often need to copy them to ensure that the sequences couldn't be modified by other code. Constructors can avoid defensive copying by only accepting tuples. Better yet, they can pass sequence arguments through the tuple method which will copy only when necessary.



回答2:


Because otherwise there wouldn't be an immutable sequence type! If you want a mutable tuple you just use a list.

Using immutable types when appropriate has various performance perks, and you couldn't easily use a dict with tuple keys if they were made mutable.



来源:https://stackoverflow.com/questions/9714815/why-tuple-is-not-mutable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!