![]() |
VOOZH | about |
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.
You can use slicing to extract parts of the string and then reassemble them as needed.
Tarun
Explanation:
Instead of modifying a string in place, you can concatenate strings to create a new one
Hello, world!
Explanation: String concatenation creates a new string since the original string is immutable and cannot be modified in place.
We can use the .join() method if we have list of strings to concatenate into a single string with desired seperator.
Hello world!
Explanation: " ".join() method combines list elements into a single string.
With the help of string formatting, we can insert the value and variable into the string
Hello Geeks For Geeks
Explanation: format() method is used to insert variable values into strings, creating a new string without modifying the original.
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: