The Immutability
Python’s string and tuple are immutable. For example
// replace a character in a string
$a = "12345";
$a[2] = "T";
You will see a TypeError when you the following in Python
# replace a character in a string (=> TypeError)
a = "12345"
a[2] = "T"
That is because strings and tuples are immutable in Python. Once created, their content cannot be changed. If so, how do we modify a string? Create a new one with updated value! Operations that seem to modify them actually create new objects in Python.
| PHP | Python |
|---|---|
Strings and arrays are mutable. You can change a character in a string by its index ($str[0] = 'H';) or directly modify array elements. |
Strings and tuples are immutable. Once created, their content cannot be changed. Operations that seem to modify them actually create new objects. |
PHP devs might try to assign to a string index (my_string[0] = 'h') in Python and get a TypeError. We need to learn patterns like string concatenation/slicing to build new strings or converting tuples to lists for modification and then back if needed. This impacts performance considerations and how data is handled. |