Immutability of strings in Python

The one interesting fact I encountered with Python is of string immutability. I’ve been programming with PHP for many years and string manipulation of a variable changes the original string – as the example below shows. The variable ‘$greetings’ has been changed.

$greetings = 'Hello World!';
$greetings[0] = 'h';
echo $greetings;
// Will display hello World!!!!

However, in Python, strings cannot be changed after they are created. You can build new strings from a existing string as every string operation produces a new string. The following example shows that. If we try to change the first character of the ‘greetings’ object, python throws an error.

>>> greetings = 'Hello World!'
>>> greetings[0] = 'h'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

You may be saying, ‘Hey, but we can do the following. Isn’t that mutating the string? Didn’t we just changed the original string?’

>>> greetings = 'Hello World!'
>>> greetings = 'Hello Earth!'
>>> greetings
'Hello Earth!'

The answer is no. Here we are not mutating a string but a variable. A variable is just a label pointing to an object (‘Hello World’). The object is immutable, but you can make the label (‘greetings’) point to a completely different object (‘Hello Earth’) if you want to.

Leave a Reply

Your email address will not be published. Required fields are marked *