What is mutability?
Simply put, a mutable object can be changed after it is created, and an immutable object can't.
Let's look back at two familiar data types: Strings and Lists. Both Strings and Lists are very familiar as they are both sequences, where Strings are sequences of letters, and Lists are sequences of various data types. However a very subtle difference between the two is mutability.
Strings are immutable, Lists are mutable
Strings can't be be directly changed, whereas lists can. This makes strings immutable and lists mutable.
Let's look at an example:
grocery_list = ['bananas', 'apples', 'cauliflower']
let's try changing
grocery_list = 'oranges' print(grocery_list)
>> ['bananas', 'oranges', 'cauliflower']
And indeed, the change occurred. Since we were able to change the list, this makes lists mutable.
Let's try the same thing with a string:
misspelled_vegetable = 'cucomber'
we purposefully misspelled the word
cucomber . Try changing the fourth character to
misspelled_vegetable = 'u'
>> TypeError: 'str' object does not support item assignment
Attempting to modify the string throws an error. The error explains that strings do not support item assignments. This makes strings immutable.
In the next article, we will look more into immutability.