String immutability in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with strings in Python, it's important to know how changes affect performance.
We want to see how the time to modify a string grows as the string gets longer.
Analyze the time complexity of the following code snippet.
text = "hello"
new_text = ""
for char in text:
new_text += char.upper()
print(new_text)
This code creates a new string by changing each character to uppercase and adding it to a new string.
- Primary operation: Looping through each character and adding to a new string.
- How many times: Once for each character in the original string.
Each time we add a character, Python creates a new string by copying the old one plus the new character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 copies (1+2+...+10) |
| 100 | About 5050 copies |
| 1000 | About 500,500 copies |
Pattern observation: The work grows much faster than the input size because each addition copies the whole string so far.
Time Complexity: O(n2)
This means the time to build the new string grows roughly with the square of the string length.
[X] Wrong: "Adding characters to a string inside a loop is fast and scales linearly."
[OK] Correct: Because strings are immutable, each addition makes a new string copying all previous characters, causing much more work as the string grows.
Understanding string immutability helps you explain why some string operations can be slow and how to write efficient code.
What if we used a list to collect characters and joined them at the end? How would the time complexity change?
Practice
immutable?Solution
Step 1: Understand the meaning of immutable
Immutable means something cannot be changed after it is made.Step 2: Apply this to strings in Python
Strings cannot be changed once created; you must make a new string to change text.Final Answer:
You cannot change a string after it is created. -> Option DQuick Check:
Immutable = cannot change [OK]
- Thinking strings can be changed like lists
- Confusing immutability with fixed size
- Believing strings store numbers only
word = 'hello' to uppercase?Solution
Step 1: Recognize string immutability
You cannot assign to a string index likeword[0] = 'H'.Step 2: Create a new string combining parts
Use slicing and concatenation:'H' + word[1:]makes a new string with first letter changed.Final Answer:
word = 'H' + word[1:] -> Option BQuick Check:
Use slicing + concat to change string [OK]
- Trying to assign directly to string index
- Using non-existent string methods like change()
- Misusing upper() which returns full uppercase
text = 'cat' text[0] = 'b' print(text)
Solution
Step 1: Identify the operation on string index
Trying to assigntext[0] = 'b'attempts to change a character in the string.Step 2: Recall string immutability rules
Strings cannot be changed by index assignment; Python raises aTypeError.Final Answer:
TypeError -> Option AQuick Check:
Index assignment on string = TypeError [OK]
- Expecting string to change without error
- Confusing TypeError with SyntaxError
- Thinking print shows changed string
word with 'J'. What is wrong and how to fix it?word = 'python' word[0] = 'J' print(word)
Solution
Step 1: Identify the error cause
Assigning toword[0]is invalid because strings cannot be changed by index.Step 2: Fix by creating a new string
Build a new string with 'J' plus the rest:word = 'J' + word[1:].Final Answer:
Strings are immutable; fix by creating a new string: word = 'J' + word[1:] -> Option AQuick Check:
Fix immutability by new string creation [OK]
- Trying to assign directly to string index
- Using replace() incorrectly for index change
- Assuming no error occurs
s = 'banana', how can you create a new string where all 'a' characters are replaced by 'o' without modifying s directly?Solution
Step 1: Understand string immutability
You cannot change characters by index; must create a new string.Step 2: Use string method to replace characters
s.replace('a', 'o')returns a new string with all 'a' replaced by 'o'.Final Answer:
s.replace('a', 'o') -> Option CQuick Check:
Use replace() to get new string with changes [OK]
- Trying to assign to string index
- Using non-existent change() method
- Changing only one character manually
