Immutability means that an object's state cannot change after creation. In Python, strings are immutable: attempting to assign through an index such as s[0] = '!' raises an exception instead of changing the string. section 2.6
Immutability affects how values are used:
- Strings, integers, Boolean values, and tuples cannot be modified in place. section 2.6 section 3.0
- Lists are mutable sequences suited to collections of similar items; tuples are immutable sequences suited to records containing different types. section 3.0
- Operations on immutable values produce new objects rather than changing the existing value. section 2.6
- Immutable values can be passed to functions without the function modifying them and shared across threads without locking for changes. section 2.6
Rebinding instead of modifying
s = 'abcd' s[0] = '!' # raises an exception t = s s = '!bcd' The last assignment binds s to a new string; it does not modify the string previously referenced by t. This replacement-oriented style also supports functional programming, which keeps data immutable and transforms inputs into outputs. section 7.0
Table 3.1 Sequence comparison (view table figure)
Compare strings, lists, and tuples by mutability, contents, syntax, and indexed retrieval. section 3.0























