String Immutability
Up to this point, we have learned that strings are easily accessible. Using square brackets [ ], we can identify and access different parts of the string, and by using the [start:stop:step] rule—referred to as slicing we can extract specific segments.
Now, we must cover a fundamental concept in programming that will become increasingly valuable to understand: Immutability.
What is Immutability?
The term immutable simply means "unchangeable." In Python, once a string is created in the computer's memory, it cannot be altered.
While you can change what a variable name points to (reassignment), you cannot reach inside a string and swap out a single character.
The Practical Example
Let's look at how this behaves in code.
Reassignment (Allowed):
count = '123456789'
print(count)
# We are telling the variable 'count' to point to a totally new value
count = '67'
print(count)
Output:
123456789
67
Mutation (Error): If you try to change just one specific index of the original string, Python will stop you.
count = '0123456789'
count[0] = '9'
print(count)
Output:
count[0]=9
~~~~~^^^
TypeError: 'str' object does not support item assignment
Why does this matter?
By making strings immutable, Python ensures that the data remains consistent and "safe" while your program runs. Because the string is stored in a fixed location in memory, Python doesn't have to worry about the data being altered unexpectedly by different parts of your code.
When we create a string in Python, that specific sequence of characters is stored in memory and cannot be changed. The only way to "change" a string is to reassign a new string to the same variable name. Since code runs line by line, the variable is updated to point to a brand-new string in memory, effectively replacing the old reference.
If you actually need to modify a piece of text (like changing one letter), you must create a new string, perhaps by using slicing and concatenation and assign that result back to your variable.
Test Your Knowledge
Select the correct answer below to see if you've mastered Python Variables.
Loading quiz...
Reassignment Using Existing Values
Another way to effectively "change" a string is to build upon its current value. For example, if you have count = '67', you can update it by writing count = count + 'r'.
When you print count, the result will be '67r'.
Time to Experiment!
Open VS Code and create a new file named immutable.py in your part15 folder. For each exercise below, write the code and use comments (#) to record your observations.
Exercise 1: The Forbidden Change
Objective: Prove that strings cannot be changed in place.
- Create a variable pet = "Cat".
- On the next line, try to change the "C" to a "B" using indexing: pet[0] = "B".
- Run the code and observe the TypeError.
- Task: Comment out the error line using # and write a comment explaining why it failed.
Exercise 2: Simple Reassignment
Objective: Change a variable's value by pointing it to a new string.
- Create a variable status = "Offline".
- Print the variable.
- Reassign status to the string "Online".
- Print the variable again to see the new value.
Exercise 3: The Accumulator
Objective: Use the current value of a variable to build a new one.
- Create a variable word = "Py".
- Use reassignment to add "th" to the end of the variable: word = word + "th".
- Use reassignment again to add "on" to the end.
- Print the final result.
Exercise 4: Slicing and Rebuilding
Objective: "Fix" a string by creating a new one from pieces of the old one.
- Create a variable movie = "Star Wars".
- Create a new variable new_movie that takes the first 4 characters of movie and adds the string " Trek" to it.
- Output should be: Star Trek
Exercise 5: Password Masking
Objective: Practice reassignment logic.
- Create a variable password = "secret123".
- Reassign the variable so that it becomes the string "**********" (10 asterisks).
- Print the variable to ensure the sensitive information is "replaced" in your variable reference.
Don't Forget to commit and Push!