Strings in Python are "immutable" i.e. they cannot be changed after they are created. Strings are immutable by design to keep them safe, consistent, and efficient. Immutability makes strings hashable (usable as dictionary keys), memory-efficient, and thread-safe, ensuring they can be reused without unexpected changes.
Example:
var="Aarun"
var [0] ='T' -> Throws: TypeError: 'str' object does not support item assignment.
Explanation: We cannot update the string after declaring it means once an immutable the objects instantiated, its value cannot be changed.
Benefits of Immutable Objects
- Hashability: Immutable objects can be dictionary keys since their hash never changes.
- Memory Efficiency: Reused by Python, saving memory.
- Thread Safety: Safe in multithreading as they can’t be modified.
- Predictability: Values stay fixed, making code easier to debug.
- Performance: Support faster lookups with cached hash values.
Ways to Deal with Immutability
String Slicing and Reassembling
You can use slicing to extract parts of the string and then reassemble them as needed.
n1 = "Aarun"
n2 = "T" + n1[1:]
print(n2)
Output
Tarun
Explanation:
- n1[1:] gives the slice of n1 from index 1 to the end of the string.
- "T" + n1[1:] concatnates 'T' in front of the sliced part and creates a new string.
String Concatenation
Instead of modifying a string in place, you can concatenate strings to create a new one
v1 = "Hello"
# Creates a new string with the concatenated result
v2 = v1 + ", world!"
print(v2)
Output
Hello, world!
Explanation: String concatenation creates a new string since the original string is immutable and cannot be modified in place.
3. Using the join() method
We can use the .join() method if we have list of strings to concatenate into a single string with desired seperator.
l1 = ["Hello", "world!"]
# Joins the list elements with a space separator
l2 = " ".join(l1)
print(l2)
Output
Hello world!
Explanation: " ".join() method combines list elements into a single string.
4. Using String Formatting
With the help of string formatting, we can insert the value and variable into the string
n1 = "Geeks"
# Insert the value of 'name' into the string using format()
n2 = "Hello {} For Geeks".format(n1)
print(n2)
Output
Hello Geeks For Geeks
Explanation: format() method is used to insert variable values into strings, creating a new string without modifying the original.
Difference between Mutable and Immutable Objects
Below is the difference between Mutability and Immutability:
Features | Mutable Objects | Immutable Objects |
|---|---|---|
Definition | Objects that can be changed after creation | Objects that cannot be changed after creation |
Examples | list, dict, set, byte array | int, float, str, tuple, bool, frozen set |
Memory Address (id) | Can remain the same after modification | Changes when a new value is assigned |
Use Case | Preferred when frequent updates are needed | Preferred when data should remain constant |
Thread Safety | Less thread-safe | More thread-safe |
Performance | May be slower due to extra safety measures | Often faster for read-only operations |
Example Code | lst = [1, 2]; lst[0] = 9 -> [9, 2] | s = "hi"; s [0] = "H" -> TypeError |
Related Articles: