Mutable vs Immutable

A mutable value can be changed after it is created; an immutable value cannot. For example, lists are mutable in Python, while strings and tuples are immutable.

General Programming

An immutable value can't be changed in place: trying, as the example does, stops with an error. Operations such as + make a new value and leave the original as it was. Immutability makes code easier to reason about, especially across multiple parts of a program.

Examples

Python

nums = [1, 2, 3]
nums[0] = 99      # OK: lists are mutable
print(nums)

text = "abc"
text[0] = "z"     # error: strings are immutable

Output:

[99, 2, 3]
TypeError: 'str' object does not support item assignment

Learn it in a lesson

See also

Back to the Dictionary