Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why tuple is not mutable in Python? [duplicate]

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?

like image 711
qazwsx Avatar asked Mar 15 '12 06:03

qazwsx


1 Answers

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.
like image 101
Daniel Lubarov Avatar answered Sep 30 '22 19:09

Daniel Lubarov