[Tutor] Mutable and Immutable data types/objects

Sean 'Shaleh' Perry shaleh@valinux.com
Sat, 12 Aug 2000 11:52:05 -0700 (PDT)

On 12-Aug-2000 Albert Antiquera wrote:
> Sorry for this very very very newbie question:
> What does mutable and immutable data types in Python really mean??What can 
> Mutable data types/objects can do that Immutable types cannot do and vice 
> versa?

starting simply:

mutable means 'able to be changed', immutable is its reverse 'constant'

simple example:

# lists are mutable
>>> list = [1, 2, 3]
>>> list[0] = 4
>>> list
[4, 2, 3]

# tuples are not
>>> tuple = (1, 2, 3)
>>> tuple[0] = 4
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment

So, the next obvious question is 'why?'.  The reason for having both a constant
data type and a mutable one is two fold: speed and expressability.

Sometimes while coding an algorithm has parts which will not change -- constant
coefficients, the value of pi, etc.  The language allows you to reflect this
and avoid accidental changing of these values.

While allowing for this, the language also has the opportunity to optimize the
constant values, since it knows they will never change.  Python does this with
strings to help string processing be faster.  An example:

in other languages if you have:

string = "dog"
string[2] = 't'
print string

Python will not allow this.  There are ways to accomplish in the language of

Hope this helps.