Python Crash Course
)}

Mutability

What is mutability?

S‍imply 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 apples to oranges.

g‍rocery_list[1] = '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 u.

misspelled_vegetable[3] = '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.

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.