Strings in Python cannot be changed. That is a stronger statement than most languages make, because it is not "changing a string is awkward" but "changing a string is impossible". It explains why s[0] = 'H' raises an error, why s += '!' can surprise you, why strings work as dictionary keys, and why building a long string by appending inside a loop is much slower than it looks like it should be. All of it falls out of one design decision.
The previous lesson in this module covered "The String Methods You Use Every Day", and the next lesson in this module is about "Searching, Counting and Replacing in Strings".
What does immutable actually mean in practice?
Every operation that looks like it edits a string actually creates a new one and gives you a reference to it. The name that you used now points at the new object. The old object is untouched, and it stays alive for as long as anything still refers to it.
text = 'hello'
print('text ->', text)
print('id before ->', id(text))
text += ' world'
print('text after ->', text)
print('id after ->', id(text))
try:
text[0] = 'H'
except TypeError as error:
print('assignment ->', error)
original = 'hello'
alias = original
alias += '!'
print('original ->', original)
print('alias ->', alias)
print('ids differ ->', id(original) != id(alias))
The last four lines are the important ones. alias and original started out pointing at the same object, so alias += '!' could have changed it in place and changed both names at once. Because strings are immutable, the operation built a new string and moved only alias to point at it. original is still 'hello', exactly as it was.
This is the same rule that you met with lists in the variables lesson, applied in the opposite direction. A list mutation changes the shared object, while a string operation replaces the reference.
Why does Python choose immutability?
Because it removes a whole category of bugs. If a value cannot change, then it is safe to hand the same value to several places at once. Nobody has to wonder whether the code on the other side of a function call changed it while you were still using it.
Three concrete benefits follow from that.
- Sharing is free and safe. A string can be passed to five functions and stored in a cache, and none of them can surprise the others.
- Strings are hashable. A hashable value can be a dictionary key or a set member, because its hash never changes. If a string could be edited in place, then every dictionary that contained it would silently break.
- Sharing across threads is safe. Two threads reading the same string cannot get in each other's way, because neither of them can write to it.
There is a practical consequence beyond safety. Because the contents of a string never change, Python can work out its hash once and then keep it, which is why using long strings as dictionary keys is cheap. It is also why the language can share a single copy of a repeated literal between several places in a program instead of storing it again and again.
import sys
first = 'hello'
second = 'hello'
print('equal strings ->', first == second)
print('same object? ->', first is second)
key = 'user-42'
records = {key: 'Ada'}
print('lookup by key ->', records['user-42'])
print('hashes agree ->', hash(key) == hash('user-42'))
shared = sys.intern('tutorsbot')
print('interned twice ->', shared is sys.intern('tutorsbot'))
The is result in the second line is true because the compiler stores each string literal once per code object, so both names refer to the same stored value. The intern() call at the end does the same thing on purpose. It asks Python to keep exactly one copy of a string in a global table, so that identical strings also match by identity. You will rarely need it, but it is the mechanism behind a surprising number of equality checks being fast.
What is the performance cost of immutable strings?
Here is where immutability stops being an abstract virtue and starts to cost you something. Because += has to create a new string, appending to a string inside a loop copies the whole thing every single time. Ten thousand appends means about fifty million character copies, and the work grows with the square of the final length.
import timeit
def build_with_plus(pieces):
result = ''
for piece in pieces:
result += piece
return result
def build_with_join(pieces):
return ''.join(pieces)
pieces = ['block'] * 2000
# The lambda is the piece of code that timeit runs again and again.
plus_time = timeit.timeit(lambda: build_with_plus(pieces), number=5)
join_time = timeit.timeit(lambda: build_with_join(pieces), number=5)
print('+= loop :', round(plus_time, 4), 'seconds')
print('join :', round(join_time, 4), 'seconds')
print('same result ->', build_with_plus(pieces) == build_with_join(pieces))
The printed timings are measured on your own machine, so the exact numbers will be different. The shape of the result does not change though. The loop that appends is dramatically slower, and the gap grows every time you double the number of pieces. join() collects the pieces first and allocates the result once, so its cost grows in proportion to the total size and not to its square.
The rule is short. One += on a string is fine and idiomatic. A += inside a loop over many pieces is a performance bug, and ''.join(pieces) is the fix.
How do you get mutable text when you need it?
Sometimes you genuinely want a buffer that you can modify in place. Python gives you several options, and each one fits a different situation.
import io
characters = list('hello')
characters[0] = 'H'
print('list of chars ->', ''.join(characters))
buffer = bytearray(b'hello')
buffer[0] = ord('H')
print('bytearray ->', buffer.decode('utf-8'))
stream = io.StringIO()
stream.write('hello ')
stream.write('world')
stream.seek(0)
print('StringIO ->', stream.read())
A list of characters is the simplest choice, and joining it at the end gives you the string back. A bytearray is the right choice for binary data that you need to edit in place, such as a chunk of a file. An io.StringIO object behaves like a file that you can write to and read back, which makes it useful for building text up in steps without touching the disk.
Reach for these when you genuinely need mutation. For everything else, the immutable version is faster and safer.
Your turn: measure and fix a slow string builder
- Write
build_slow(pieces)that appends with+=inside a loop, andbuild_fast(pieces)that usesjoin(). Confirm that both return the same string for a list of a hundred words. - Time both of them with
timeitat three sizes: 100, 1000, and 5000 pieces. Print the ratios and note how the gap widens. - Confirm that the
+=version is quadratic by printing, in plain text, how the time changes when you double the size. If doubling the input more than doubles the time, then you have quadratic behaviour. - Write a third version that collects the pieces in a list and joins them once at the end. Check that it matches the other two exactly, including for an empty input list.
- Finally, use
sys.getsizeof()on the result of a small join to see the size of the final string, and explain in a comment why the+=version allocated far more memory along the way, even though both of them end up with the same string.
Why immutability matters
- Strings never change, so every "edit" creates a new object and rebinds the name.
- That makes strings safe to share, safe to use as dictionary keys, and safe to pass between threads.
- Two identical literals are usually the same object, and
sys.intern()asks for that on purpose. - Appending inside a loop copies the whole string each time, so build long strings with
join(). - Use a list, a
bytearray, or anio.StringIOwhen you genuinely need to edit text in place.