Open In App

Why are Python Strings Immutable?

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Strings in Python are “immutable” which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc. 

The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc.

The article will explore the differences between mutable and immutable objects, highlighting the advantages of using immutable objects. It will also compare immutability with mutability, discussing various methods to handle immutability and achieve desired outcomes.

Input:  name_1 = "Aarun" 
name_1[0] = 'T'
Output: 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

Python Strings Immutability

Immutability is the property of an object according to which we can not change the object after we declared or after the creation of it and this Immutability in the case of the string is known as string immutability in Python.

Work with Mutable and Immutable Objects

The immutable term generally refers to their property of being immune to change or modification after their creation, the same case with the string data type in Python which is immutable.

Some other datatypes in Python are immutable such as strings, numbers (integers, floats, complex numbers), tuples, and frozensets.

Mutable objects are that we can modify according to our requirements and use according to our use. A few examples of them are List, Dictionary, and Set.

Example:

In the below code, we declare a string and assign it to modify the “my_string” variable, after that we try the string.

Python3




my_string = "Hello, world!"
 
# Attempt to modify the string
my_string[0] = 'h'  # Raises TypeError: 'str' object does not support item assignment-----


Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
my_string[0] = 'h' # Raises TypeError: 'str' object does not support item assignment-----
TypeError: 'str' object does not support item assignment

Benefits of Immutable Objects

  1. Hashability and Dictionary Keys: Immutable objects can be used as keys in dictionaries because their hash value remains constant, ensuring that the key-value mapping is consistent.
  2. Memory Efficiency: Since immutable objects cannot change their value, Python can optimize memory usage. Reusing the same immutable object across the program whenever possible reduces memory overhead.
  3. Thread Safety: Immutability provides inherent thread safety. When multiple threads access the same immutable object, there’s no risk of data corruption due to concurrent modifications.
  4. Predictability and Debugging: With immutability, you can be confident that a given object’s value will not change unexpectedly, leading to more predictable and easier-to-debug code.
  5. Performance Optimization: Immutable objects facilitate certain performance optimizations, such as caching hash values for quick dictionary lookups.

Difference between Immutability and Mutability

Here we will discuss what is the key difference between mutability and immutability, with a proper example.

1. Mutability: Mutable objects are those objects that can be modified after their creation, to demonstrate mutability in Python we have a very popular data type which is the list.

Example:

Python3




my_list = [1, 2, 3]
print("Valid operation, modifying the first element of the list")
my_list[0] = 10


Output:

Valid operation, modifying the first element of the list
[10, 2, 3]

2. Immutability:

Immutability refers to the property of an object, that we can not change the object after we declare it.

Python3




my_string = "GeekGeek"
 
# Attempt to modify the string
my_string[0] = 'for'  # Raises TypeError: 'str' object does not support item assignment
#this will give an typeError


Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
my_string[0] = 'for' # Raises TypeError: 'str' object does not support item assignment
TypeError: 'str' object does not support item assignment

For More Details Read – Mutable vs Immutable Objects in Python

Ways to Deal with Immutability

  • String Slicing and Reassembling
  • String Concatenation
  • Using the join() method
  • Using String Formatting
  • Converting to Mutable Data Structures

1. String Slicing and Reassembling:

You can use slicing to extract parts of the string and then reassemble them as needed

Python3




name_1 = "Aarun"
 
name_2 = "T" + name_1[1:]
 
print("name_1 = ", name_1, "and name_2 = ", name_2)


Output:

name_1 =  Aarun and name_2 =  Tarun

2. String Concatenation:

Instead of modifying a string in place, you can concatenate strings to create a new one

Python




my_string = "Hello"
new_string = my_string + ", world!"  # Creates a new string with the concatenated result
print("This is our new string with the concatenated result")
print(new_string)


Output:

This is our new string with the concatenated result
Hello, world!

3. Using the join() method:

We can use the join() method if we have multiple strings to concatenate.

Python3




my_list = ["Hello", "world!"]
new_string = " ".join(my_list)  # Joins the list elements with a space separator
print("Joins the list elements with a space separator")
print(new_string)


Output:

Joins the list elements with a space separator
Hello world!

4. Using String Formatting

Here with the help of string formatting, we can insert the value and variable into the string

Python3




name = "Geeks"
new_string = "Hello {} ".format(name)
# Output: "My name is John and I am 30 years old."
print(new_string)


Output:

Hello Geeks

5. Converting to Mutable Data Structures

We can also convert the immutable data type to the mutable data type so that we can perform the desired operation on that data type.

Python




my_string = "Hello, world!"
my_list = list(my_string)
my_list[0] = 'h'
new_string = "".join(my_list)  # "hello, world!"
print(new_string)


Output:

hello, world!

In this article, we have covered mutable and immutable objects in Python. We saw examples of each with examples, we also checked key differences between mutable and immutable objects.

Immutability is very important in Python, as it helps in data safety and interpreter performance. The string data type is very common in Python programs hence they are immutable.

Similar Read:

Why do we Need Immutables in Python



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads