In Python, strings are immutable — you cannot change them in place.
So:
s = "hello"
s[0] = "H" # ❌ TypeError: 'str' object does not support item assignment
✅ Correct ways to make "Hello"
:
s = "hello"
# Method 1: Concatenate
s = "H" + s[1:]
print(s) # Hello
# Method 2: Using str.replace (only first character)
s = s.replace("h", "H", 1)
print(s) # Hello
# Method 3: Convert to list, modify, then join
lst = list("hello")
lst[0] = "H"
s = "".join(lst)
print(s) # Hello
🔹 Reasons why Python strings are immutable
- Memory efficiency & interning
- Python often reuses the same string object internally (string interning).
- Example:
a = "hello" b = "hello" print(a is b) # True → both point to same object
- If strings were mutable, changing
a
would accidentally changeb
. Immutability prevents this.
- Hashing & Dictionary keys
- Strings are commonly used as keys in dicts and elements in sets.
- Hash-based collections require objects to be immutable (hash must stay stable).
- Example:
d = {"hello": 123} # If "hello" could mutate into "hellx", its hash would change → dict lookup breaks.
- Thread-safety
- Multiple threads can safely share string objects since they can’t be changed.
- No need for locks or synchronization just for reading strings.
- Predictability & simplicity
- If strings were mutable, debugging would be harder because one function might unexpectedly change a string that another function relies on.
- Immutability makes behavior more predictable and aligns with Python’s philosophy: “Simple is better than complex.”
- Encourages functional style
- You build new strings from old ones instead of altering in place, which leads to cleaner, bug-resistant code.
👉 That said, if you really need a mutable sequence of characters, Python provides:
list
of characters:list("hello") → ['h', 'e', 'l', 'l', 'o']
bytearray
(mutable version of bytes).
⚡ Quick analogy:
Think of strings like numbers — 5
is immutable. If you do x = 5; x += 1
, Python gives you a new 6
. Same with "hello" → "Hello"
.