Immutability is the property of an object or value whose state cannot be modified after creation. Python strings and tuples are immutable: changing them requires creating or assigning a new value. section 8.1 section 22.1.1
In Python, immutability changes how programs update data:
- Rejects item assignment on strings and tuples instead of changing their contents. section 10.1.4 section 22.1.1
- Produces a new string through methods such as str.replace(), str.translate(), or string reconstruction. section 8.6 section 8.1.1
- Contrasts with mutable lists, which can be edited in place and later joined into a string. section 10.3.2
- Supports tuples and named tuples when data should not be accidentally modified during program execution. section 22.1.2
Rebuild an immutable string
>>> text = 'The quick brown fox.' >>> text[2] = 'i' TypeError: 'str' object does not support item assignment >>> text = text[:2] + 'i' + text[3:] >>> text 'Th i quick brown fox.' For repeated character edits, convert the string to a list, modify the list, and use ''.join(text) to create a new string. section 10.1.4 section 10.3.2
>>> state[1] = 'O' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
Observe the TypeError produced when tuple item assignment attempts to modify an immutable value. section 22.1.1























