7

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?

Community
  • 1
  • 1
qazwsx
  • 25,536
  • 30
  • 72
  • 106

2 Answers2

27

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.
Daniel Lubarov
  • 7,796
  • 1
  • 37
  • 56
  • Their hash values can change? Huh? – wim Mar 15 '12 at 06:25
  • 2
    wim -> hash vaules change when list change. List can change if there is a ref somewhere else to the list. – Esben Skov Pedersen Mar 15 '12 at 06:29
  • Can you detail what "they (constructors) can wrap sequence arguments in tuple which will copy only when necessary" means? – qazwsx Mar 16 '12 at 02:41
  • Normally, `tuple(..)` creates a new tuple object, copying each element from the given iterable (typically a list). But if the argument is already a tuple, that tuple is just returned and no copying takes place. – Daniel Lubarov Mar 16 '12 at 07:55
  • A set member is just one of the objects contained in a set. The point I wanted to make was just that Python doesn't allow sets like `{[]}`, because Python's set implementation relies on consistent hashing, and mutable objects like lists are not hashable. – Daniel Lubarov Mar 16 '12 at 07:58
1

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.

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
wim
  • 338,267
  • 99
  • 616
  • 750