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



Previous Article
Next Article

Similar Reads

Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Why does comparing strings using either '==' or 'is' sometimes produce a different result in Python?
Python offers many ways of checking relations between two objects. Unlike some high-level languages, such as C++, Java, etc., which strictly use conditional operators. The most popular operators for checking equivalence between two operands are the == operator and the is operator. But there exists a difference between the two operators. In this art
4 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = &quot;10&quot; # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Why is python best suited for Competitive Coding?
When it comes to Product Based Companies, they need good coders and one needs to clear the Competitive Coding round in order to reach the interview rounds. Competitive coding is one such platform that will test your mental ability and speed at the same time. Who should read this? Any programmer who still hasn't tried python for Competitive Coding M
7 min read
Why Python is called Dynamically Typed?
Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable, just an assignment statement. Let us see why? When we declare a variable in C or alike languages, this sets aside an area of memory for holding values allowed by the data type of the variable. The memory allocated
2 min read
Why import star in Python is a bad idea
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from w
3 min read
Article Tags :
Practice Tags :