AI Hints
Home›DSA in Python Tutorial›Array Practice
DSA in Python · Lesson 18 of 132

Strings Are Immutable

Building strings efficiently.

⏱ 2 min read▶ Video at 20:40🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

In Python, a string can never be changed. Every time you seem to change one, Python actually builds a brand new string. That's usually fine, but inside a big loop, it can quietly make your code slow.

Strings Are Immutable
From the video: Strings Are Immutable
  • Strings never change
  • Python builds a new one
  • Slow inside big loops

Changing a string fails

Try to change the first letter of a string, and Python refuses, with a type error. To get a different string, you must build a new one. Here, slicing plus a new first letter. Run it.

immutable.pypython
word = "cat"
try:
    word[0] = "b"
except TypeError as e:
    print("Python says:", e)

word = "b" + word[1:]
print(word)
Output
Python says: 'str' object does not support item assignment
bat

Plus equals versus join

Here we build a long string from a hundred thousand pieces, two ways. Plus equals in a loop, and join, which collects the pieces in a list and glues them together once at the end. Run it. Join is the reliable, fast way. Python can sometimes speed up plus equals, but you can't count on it.

join.pypython
import time
pieces = [str(i) for i in range(100_000)]

start = time.perf_counter()
s = ""
for p in pieces:
    s += p
print(f"+= loop: {time.perf_counter() - start:.4f} s")

start = time.perf_counter()
s2 = "".join(pieces)
print(f"join:    {time.perf_counter() - start:.4f} s", s == s2)
Output
+= loop: 0.4890 s
join:    0.0007 s True

Summary

Strings are immutable, so every change builds a new string. To build a big string, collect pieces in a list, and join them once. Next, a new section. Hash tables, the most useful data structure of all.

Key takeaways
  • Strings can't change
  • Build new strings
  • Use join for many pieces
Next up: Hash Tables — the magic behind dict and set