Mutation

From CS 61A Wiki
Jump to: navigation, search

A mutation is the act of changing an object's attributes over time. Mutable objects that are passed into a function can be changed and returned. In Python, 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.

Lists

Lists are mutable objects that can be modified by its object methods.[1] When two variable names reference the same list and the list is then mutated, referencing the list from either name will reflect the mutation.

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

Rules that normally apply to objects regarding identity and equality also apply to mutable data. Two separate lists that have the same contents are equal but not identical.

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

Immutability

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]
'h'
>>> 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'

Sources

  1. https://docs.python.org/2/tutorial/datastructures.html
  2. http://www-inst.eecs.berkeley.edu/~selfpace/cs9honline/Q2/mutation.html