Beginner   Chapter 39 · 20 min read · Module 3: Python Strings

String Immutability

Learning objectives
  • After this chapter you can explain what it means that strings are immutable.
  • You can recognise the TypeError raised when you assign to a character of a string.
  • You can create changed copies of a string using slicing, concatenation and string methods.
  • You can use id() to see that a new string is a different object.
  • You can build large strings efficiently with join().

In Python, a string is a fixed sequence of characters. Once a string is created, you cannot change one of its characters, remove a character, or insert a new one into the same object. This property is called immutability, and it is one of the first surprises for people who come from other ways of thinking about text.

This does not mean you cannot work with changed text. It means that every change gives you a brand new string, and the old one stays as it was. Methods such as upper(), replace() and strip() all follow this rule: they return a new string and leave the original alone.

In this chapter you will see the error that Python shows when you try to change a string in place, learn the safe ways to get the result you want, and understand why this design is useful for dictionary keys, safe sharing and predictable programs.

What does immutable mean?

An object is immutable when its content cannot change after it is created. Numbers, strings, tuples and booleans are immutable in Python. A list is the opposite: it is mutable, so you can change its items. When you write word = "cat", Python builds a string object holding the three characters. That object will stay cat for as long as it exists.

Immutable: describes an object whose value cannot be changed after it is created; any change produces a new object

Many beginners think that a line such as word = "dog" changes the string. It does not. It makes the name word point to a different string object. The old string cat is simply no longer used by that name. This difference between changing an object and rebinding a name is the key idea of the whole chapter.

The error you get when you try

If you try to assign to an index of a string, Python raises a TypeError. The message says that the str object does not support item assignment. The same is true for deleting a character with del. The example below catches the error so that you can see the message.

Example 1: assigning to a character fails
word = "cat"
try:
    word[0] = "b"
except TypeError as err:
    print("Error:", err)
print(word)
Error: 'str' object does not support item assignment cat

Notice that the string is still cat after the failed attempt. Python refused to change it. Reading a character, such as word[0], is always allowed because reading does not modify anything.

Making a changed copy

To get the text you want, build a new string from parts of the old one. Slicing lets you take the pieces before and after the character you want to change, and then you join them with the new character in the middle. The string method replace() does a similar job when you know which text to replace.

Example 2: build a new string
word = "cat"
new_word = "b" + word[1:]
print(new_word)
print(word)
print(word.replace("c", "h"))
print(word.upper())
print(word)
bat cat hat CAT cat

The original word is printed again and is still cat. Every call returned a new value. If you want to keep the new value, you must store it, for example word = word.upper(). Forgetting to store the result is one of the most common string mistakes.

Seeing new objects with id()

The built-in id() function returns a number that identifies an object while it exists. You do not need to learn the exact numbers. You only need to compare them. If two names have the same id, they point to the same object. After a change to a string, the id differs, which proves a new object was made.

Example 3: the object changes, not the content
s = "hello"
before = id(s)
s = s + " world"
after = id(s)
print(s)
print(before == after)
hello world False
The actual id numbers differ from computer to computer and from run to run, so compare them with == instead of printing them.

Building big strings with join()

Because each + creates a new string, adding many small pieces in a long loop makes Python copy text again and again. A cleaner and faster habit is to collect the pieces in a list and call "".join(pieces) once at the end. The text before .join is the separator that goes between the pieces. An empty string means no separator.

Example 4: join the pieces
letters = []
for ch in "python":
    letters.append(ch.upper())
print("-".join(letters))
print("".join(letters))
P-Y-T-H-O-N PYTHON

Why are strings immutable?

  • Safety: a string passed to a function cannot be changed behind your back.
  • Dictionary keys: only objects that cannot change can be used as keys, so strings work well there.
  • Speed and memory: Python can reuse the same string object in several places.
  • Simplicity: you never need to ask whether some other part of the program modified your text.

Immutable name, mutable list

When you really need to edit characters one by one, convert the string to a list with list(text), change the list, and join it back into a string. The list is a separate object, so the original string is never touched.

Example 5: edit through a list
text = "cat"
chars = list(text)
chars[0] = "b"
result = "".join(chars)
print(result)
print(text)
bat cat

Python syntax

Syntax
new_text = old_text[:i] + new_char + old_text[i+1:]
Syntax
new_text = old_text.replace(old, new)
Syntax
result = separator.join(list_of_strings)
Syntax
chars = list(text); chars[i] = x; text = "".join(chars)

Real-world applications

  • Cleaning user input with strip() and lower() without damaging the original data.
  • Using words or IDs as dictionary keys safely.
  • Building reports and file lines from many small pieces with join().
  • Writing functions that take text and return a modified copy.

Common mistakes

Mistake: Writing text[0] = "X" and expecting the string to change.
Fix: Build a new string with slicing, replace(), or edit a list of characters and join it.
Mistake: Calling text.upper() on its own line and expecting text to change.
Fix: Store the result: text = text.upper().
Mistake: Joining with + inside a very long loop.
Fix: Collect pieces in a list and call "".join(pieces) once.
Mistake: Thinking that rebinding a name modifies the old string.
Fix: Remember that name = new_value only points the name to another object.

Important tips

  • Read the method name: methods on strings always return a new string.
  • Use list(text) when you need many in-place style edits.
  • Use == to compare strings and id() only to learn how objects behave.

Key points summary

  • Strings are immutable: their characters cannot be changed in place.
  • Item assignment on a string raises TypeError.
  • String methods return new strings and never modify the original.
  • Rebinding a name is not the same as changing an object.
  • join() is the right way to build a string from many pieces.

Exam and interview points

  • Name the immutable built-in types: int, float, bool, str, tuple.
  • The error for text[0] = 'x' is TypeError: 'str' object does not support item assignment.
  • String methods return new strings.
  • Explain the difference between changing an object and rebinding a name.

Quick revision

  • str is immutable.
  • text[i] = x raises TypeError.
  • Make a new string with slicing, replace() or join().
  • Store method results or they are lost.
  • Use "".join(list) for many pieces.

Frequently asked questions

Can I delete a character from a string?

Not in place. You can create a new string without it, for example text[:2] + text[3:], or use replace().

Is a += "x" a change to the same string?

No. It creates a new string and makes the name point to it. For strings the old object stays unchanged.

Why does a list allow item assignment but a string does not?

A list is mutable by design, while a string is immutable. This makes strings safe to share and to use as dictionary keys.

Does immutability make strings slow?

Not in normal use. Only huge loops that add pieces with + need care, and join() solves that.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters