Sub topic 12
Why Strings Are Immutable
This chapter explains what it means for a Python str to be immutable, what happens when code seems to change a string, and why the language works this way. It assumes you can run Python, use print(), and index and slice strings (s[0], s[1:4]). It also assumes you know that an assignment binds a name to an object.
What immutable means
An immutable object cannot change after it is created. Every str has this property. No operation can alter a character inside an existing string, add to it, or remove from it.
s = "Python"
print(s[0])
print(s[-1])
print(s[1:4])
print(s[::-1])
try:
s[0] = "J"
except TypeError as e:
print("TypeError:", e)
print("J" + s[1:])Reading works. Indexing and slicing each return a new string. Assigning to s[0] raises TypeError with the message 'str' object does not support item assignment. The same applies to del s[0], and strings have no append, insert, or pop.
The last line shows the usual way to get a "changed" string. You build a new string from pieces of the old one.
Rebinding is not mutation
This is where most confusion comes from. The following code looks like it modifies a string, but it does not.
s = "Python"
t = s
s = "J" + s[1:]
print(s)
print(t)
print(s is t)
before = id(s)
s += "!"
print(id(s) == before)The output is Jython, Python, False, False.
t = smakes a second name for the same object.s = "J" + s[1:]builds a new string object and rebindssto it. The old object still exists, andtstill points to it.s += "!"is also rebinding. For an immutable type, augmented assignment creates a new object and moves the name. Theid()check confirms thatsnow refers to a different object.
Compare this with the list example from the identity chapter. With a list, b = a followed by b.append(3) changes the one shared object, and a sees it. With a string, no operation can change the shared object, so two names referring to one string can never surprise you. Sharing is safe because nothing can change underneath you.
Methods return new strings
String methods follow the same rule. They never modify the string they are called on.
name = "ada lovelace"
name.upper()
print(name)
name = name.upper()
print(name)The first print shows ada lovelace. The call name.upper() produced a new string, but nothing captured it, so it was discarded. This is a common beginner bug. The fix is to bind the result: name = name.upper().
| Operation | Works on `str`? | Why |
|---|---|---|
| `s[0]` | Yes | Reading returns a new one-character string |
| `s[1:4]` | Yes | A slice is a new string |
| `s[0] = "J"` | No | `TypeError`, item assignment is unsupported |
| `del s[0]` | No | `TypeError`, item deletion is unsupported |
| `s.upper()` | Yes | Returns a new string, `s` is unchanged |
| `s += "!"` | Yes | Builds a new string and rebinds `s` |
Why Python makes strings immutable
The design has practical reasons.
- Strings can be dictionary keys and set members. A dictionary finds a key using its hash, a number computed from the contents. If a key could change after insertion, its hash would change and the entry could never be found again. Immutable objects have stable hashes, so strings are hashable. Lists are mutable and are not.
- Hashes can be cached. Because the contents never change, CPython computes a string's hash once and reuses it. Dictionary lookups with string keys stay fast.
- Sharing is safe. The interpreter can reuse one string object in many places, such as identifiers, attribute names, and short literals, without copying. No part of a program can corrupt a string that another part is using.
- Concurrent code is simpler. Threads can read the same string without locks, because no thread can modify it.
- Fewer aliasing bugs. Passing a string to a function never lets the function change your copy.
prices = {"Ada": 10}
key = "Ada"
print(prices[key])
try:
broken = {["Ada"]: 10}
except TypeError as e:
print("TypeError:", e)The dictionary lookup prints 10. The list key fails with TypeError: unhashable type: 'list'.
The cost: repeated concatenation
Each "change" allocates a new string and copies the characters. That is cheap once, but it adds up in a loop that appends thousands of times. Each step copies everything built so far, so total work grows roughly with the square of the final length. CPython sometimes optimizes result += piece when only one name refers to the string, but this is an implementation detail. Other Python implementations do not guarantee it.
The portable pattern is to collect pieces in a list, which is mutable and appends cheaply, and join once at the end.
parts = []
for i in range(5):
parts.append(str(i))
print(",".join(parts))This prints 0,1,2,3,4. The join copies each character once.
If you need character-level editing, convert to a list, edit, and join back.
chars = list("Python")
chars[0] = "J"
print("".join(chars))This prints Jython. For building large text incrementally, io.StringIO is another option. It is a file-like object with a write method and a getvalue() method that returns the text.
Gotchas and edge cases
- Immutable object, rebindable name. Immutability is a property of the string object, not of the name. A name can always be rebound to a different string. Writing a name in capitals does not stop that.
- Compare strings with
==, notis.==compares contents.iscompares object identity. CPython may reuse (intern) equal strings, soa is bcan beTruefor some strings andFalsefor others. The result depends on how each string was created and on the interpreter version. Never useisto test string equality. - Forgetting to capture the result. Calls like
s.strip()ors.replace("a", "b")on their own line do nothing useful. This is the most common mistake. - A new object each time, even for no-ops. Do not assume
s.strip()returns the same object when there is nothing to strip. Code should not depend on that either way. - Other immutable types.
bytes,tuple,int,float, andboolare immutable too.bytearrayis the mutable counterpart ofbytes. - Mutable contents inside immutable containers. A tuple is immutable, yet it can hold a list that you can still change. A string holds only characters, so this case does not arise for
str.
Exercise
After running a = "cat", b = a, a = a + "s", what do a and b contain, and why?
Show answer
a is "cats" and b is "cat". a + "s" creates a new string object and a is rebound to it. The original "cat" object is unchanged, and b still refers to it.
Exercise
This code is meant to uppercase a title but prints it unchanged: title = "intro" then title.upper() then print(title). Explain the bug and fix it.
Show answer
title.upper() returns a new string and the result is discarded, because strings cannot be modified in place. Fix it by rebinding: title = title.upper(). Then print(title) shows INTRO.
Exercise
Write code that replaces the first character of "hello" with "J" using a list, and prints the result. Why is a list needed?
Show answer
chars = list("hello"), then chars[0] = "J", then print("".join(chars)), which prints Jello. A list is mutable and supports item assignment. A string does not, so you edit a list of characters and join it back into a new string.