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.
>>> 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 >>> c = [1, 2, 3, 4] >>> a == c True >>> a is c False
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 'h' >>> a = '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.
>>> a = 'hello' >>> a += ' world' >>> a 'hello world'