Lists and Mutability
Immutability is a feature rather than merely a restriction.
The tempting assignment
When you learn indexing, it is natural to think that reading and changing should work in similar ways. You can read the first character of greeting with greeting[0]. It may therefore seem reasonable to write greeting[0] = 'J' when changing Hello to Jello. Python does not permit this operation because strings are immutable.
What do you think happens?
What happens when Python evaluates greeting[0] = 'J' for the string Hello?
Reveal answer
Python raises a TypeError.
A string does not support assignment to one of its items. The attempted assignment targets the character at index 0, but string contents cannot be modified in place.
The failed string update
TypeError: 'str' object does not support item assignmentThe error message identifies the problem precisely. The object is the string value greeting. The item is the individual character at index 0. Python is telling you that a string object does not allow a new value to be assigned to one of its items. The assignment fails at that statement, so the attempted character replacement does not occur.
What immutable means
Immutable means that once a string has been created, its contents cannot be changed. Reading characters from a string is allowed, but assigning a new value to one of those characters is not.
Immutability does not mean that you can never have a different string. It means that the existing string remains unchanged. To produce a variation, take the parts you want to keep, add the replacement content, and create a new string. The result can be stored under a new variable name or assigned back to the same variable name.
Building a replacement
Changing Hello to Jello
Create a new string whose first character is J while keeping the rest of Hello.
- 1Keep the part before the replacement
The portion before index 0 is empty, so there is no earlier text to keep.
- 2Choose the replacement content
Use the new character J.
- 3Keep the remaining portion
Use the part of the original string after its first character, which is ello.
- 4Join the parts
Concatenate the kept portion, the replacement character, and the remaining portion to produce Jello.
The new string is Jello, while the original string value Hello remains unchanged.
Hello
JelloReassigning the same name
greeting = 'Hello'
greeting = greeting[:0] + 'J' + greeting[1:]
print(greeting)- 1The first line creates the original string value Hello.
- 2The second line reads parts of the original and combines them with J. The resulting string is Jello, and the variable name is assigned that result.
- 3The final line displays the new value associated with greeting.
- The variable greeting is first associated with Hello.
- Slicing and concatenation produce a new string variation.
- The variable name greeting is then associated with the new string value.
- The original string was not modified in place.
JelloUsing the same variable name can make the operation look like a mutation, but the mechanism is different. Python first builds a new string from slices and concatenation. Then the name can be assigned to that new result. The earlier string itself remains immutable.
Strings beside lists
| Operation | String | List |
|---|---|---|
| Read an item at a position | Allowed | Allowed |
| Replace an item at a position | Not allowed; raises TypeError | Allowed in the mutable-list comparison |
| Produce a changed sequence | Create a new string with slicing and concatenation | Replace the item in the list |
The important distinction is that strings are immutable, while lists are used as the mutable comparison in this topic.
Why immutability helps
Immutability is a feature rather than merely a restriction. Python can safely use strings as dictionary keys because their contents cannot change after they are used as keys. Immutability can also allow memory optimization when two variables reference the same string value. In addition, a function that receives a string cannot accidentally alter that string and affect code elsewhere in the program.
Common assignment mistakes
Common mistake Trying to replace a string character with item assignment.
What it looks likegreeting[0] = 'J'Why it failsStrings are immutable, so a string does not support assignment to one of its items.
Do this insteadUse slicing and concatenation to build a new string.
Common mistake Assuming that reading an indexed character means the character can also be changed.
What it looks likeReading greeting[0] works, so changing greeting[0] should work too.
Why it failsReading an item and assigning a new item are different operations. Python allows the read but rejects the string item assignment.
Do this insteadTreat indexed string access as a way to inspect a character, not as permission to replace it.
Common mistake Thinking that assigning the new result back to the same variable mutates the original string.
What it looks likegreeting = greeting[:0] + 'J' + greeting[1:]Why it failsThe expression creates a new string variation before the variable name is assigned that result.
Do this insteadRecognize the operation as creating a new string and then assigning the variable name to it.
Practice the distinction
For the code below, predict which line raises an error. Then rewrite the code so that the final value displayed is Jello without using item assignment.
greeting = 'Hello'
greeting[0] = 'J'
print(greeting)Hints
- The error is raised when the code attempts to assign a value to one character.
- Keep the part after the first character and concatenate it with J.
- The corrected version must create a new string variation.
JelloKey takeaways
- 1Strings are immutable: once created, their contents cannot be changed.
- 2Assigning a new value to a string character raises
TypeErrorwith the message 'str' object does not support item assignment. - 3Slicing and concatenation create a new string variation from selected parts of the original and new content.
- 4Assigning the new result back to the same variable name does not change the original string in place.
- 5Immutability supports safe dictionary keys, memory optimization, and protection against accidental changes.
At a glance
- Strings cannot be modified after creation.
- String item assignment raises a
TypeErrorbecause strings do not support changing individual characters. - Use slicing and concatenation to create a new string variation.
- Reassigning a variable to the new string is different from mutating the original string.
- String immutability provides useful safety and implementation benefits.