Why strings are immutable in python?

Anantha Kattani
2 min readApr 7, 2022

Strings have been one of the basic things to know in python. Making the basics strong can help you in mastering python.

Initializing a string and checking the memory location using ‘id*’.

When we initialize a string as given above. It creates an object and the variable “string” will hold the references to the memory location where ‘Hello World’ is stored.

Remember: string variable will not hold the value ‘Hello World’ but the address of the memory location.

When we reinitialize the same variable to a different string it creates a new object and stores the memory location of that string. It does not modify the previous object “Hello world”. It creates a new object. That is why strings are immutable.

Initializing a new string to the same variable.

Why?

Its simple, to reduce unnecessary bugs.

Properties of Being Immutable:

Once a string is created you can’t edit the strings and change it into a different string.

Getting a typeerror for the immutability property.

If you want to store the changed value of the string, then you have to initialize a new variable. Once created u can never change a string. You can only delete it as a whole.

Additional Information -

If 2 variables are equal to the same string they will be pointing to the same memory location.

As you can see both the variables will be pointing to the same memory location of ‘Hello World’.

Other Immutable Objects in Python:

Integer, Float, Tuple, Bool.

*id()- It specifies the memory location where the value is stored.

--

--

Anantha Kattani

Let's create good machine learning projects to create a positive change in the society.