Sub topic 12
Why strings are immutable
This chapter assumes you know that a name is bound to an object, that + joins strings, and that slicing returns part of a string. It explains what it means that a str cannot change, and how to work with that.
What immutable means
An immutable object cannot be modified after it is created. Every operation that looks like a change produces a new object. Strings, ints, floats, and tuples are immutable. Lists and dictionaries are mutable.
s = "Python"
try:
s[0] = "J"
except TypeError as e:
print("TypeError:", e)
print("J" + s[1:])
print(s)The assignment to s[0] raises TypeError: 'str' object does not support item assignment. The expression "J" + s[1:] builds a new string, and s still holds Python.
Methods return new strings
Every string method returns a new string and leaves the original alone. The most common mistake is calling a method and discarding the result.
name = "ada"
name.upper()
print(name)
name = name.upper()
print(name)The first print shows ada, because the result of name.upper() was thrown away. The second shows ADA, because the name was rebound to the new string.
Rebinding is not mutation
Augmented assignment on a string also creates a new object. A second name bound to the old string keeps the old value.
a = "ab"
b = a
a += "c"
print(a, b)
print(a is b)This prints abc ab and then False. The += built a new string and rebound only a. With a list, a += [x] would instead extend the shared object in place, so both names would see the change.
Building text efficiently
Because each += may copy the whole string, building a long string in a loop can be slow. Collect the pieces in a list and join them once.
parts = []
for i in range(3):
parts.append(str(i))
print("-".join(parts))This prints 0-1-2. If you need to edit individual characters, convert to a list, change it, and join it back.
chars = list("Python")
chars[0] = "J"
print("".join(chars))This prints Jython.
Why Python works this way
- Hashability. A dictionary key must keep the same hash for as long as it is stored. An immutable string guarantees this, so strings work as keys and set members.
- Safe sharing. Many names can refer to one string, and no name can change it for the others.
- Optimization. CPython can reuse identical short strings. This is safe only because nobody can modify them.
d = {"id": 7}
print(d["id"])The trade-off is that every edit allocates a new string. For small strings this cost does not matter.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| `s[0] = "J"` | `TypeError` | Build a new string with slicing and `+` |
| `s.strip()` with no assignment | Text unchanged | `s = s.strip()` |
| `+=` in a large loop | Slow code | Use a list and `"".join(...)` |
| Comparing text with `is` | Unreliable result | Use `==` |
Exercise
A learner writes title = " report ", then title.strip(), then print(title). The output still has the spaces. Why, and what is the fix?
Show answer
Strings are immutable, so strip() returns a new string and leaves title unchanged. The new string was discarded. Write title = title.strip() to rebind the name to the result.
Exercise
Given word = "cat", write one expression that produces "bat" without assigning to an index.
Show answer
"b" + word[1:]. Slicing from index 1 gives "at", and "b" + "at" builds the new string "bat".