From CS 61A Wiki
Revision as of 15:39, 20 July 2014 by Alc (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jump to: navigation, search

A mutation is the act of changing an object's attributes. Mutable objects that are passed into a function can be changed and returned. For example, a list is a mutable data structure whose contents can be changed by appending, popping, and performing various additional operations. Custom classes are also generally mutable unless explicitly defined to be immutable.


In Python, lists are mutable objects that can be modified by its object methods.[1]

>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> a == b
>>> a is b
>>> c = [1, 2, 3, 4]
>>> a == c
>>> a is c


In Python, not everything is mutable. Strings, numbers, tuples, booleans, and other types of objects are immutable. Once they are formed, their contents cannot be altered, though they can be used to form new objects. Immutable objects that are passed into functions and changed do not reflect those modifications after the function has completed.

In the following example, characters in a string cannot be redefined because attributes of an immutable string object cannot be altered.

>>> a = 'hello world'
>>> a[0]
>>> a[0] = 'H'
Traceback (most recent cal last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

However, immutable objects can still be reassigned to other variables. In the following example, a initialy references the 'hello' string. The ' world' string is then concatenated to 'hello' and assigned to a, which changes what a is referencing but does not change the actual value of either the 'hello' or ' world' strings.[2]

>>> a = 'hello'
>>> a += ' world'
>>> a
'hello world'