Python Crash Course
)}

Mutability II

Previously we concluded that strings are immutable, where as lists are mutable. If you're still confused as to why that is, make sure to revisit that lesson.

‍How does immutability affect the behaviour of the data type‍s?

Immutable Data Type

let's explore an example with the immutable data type string:

name = 'John' other_name = name name = 'Jane'
  1. We just assigned name to John
  2. then we assigned other_name to name
  3. then we changed the variable name to Jane

W‍hat can we expect when we print both name and other_name?

print(name) print(other_name)

‍>> Jane

>> John

Even though we updated the value of name, the change was not reflected on other_name.

Mutable Data Type

Let's look and see if this behaviour applies to mutable objects such as lists:

fruits = ["apples", "oranges", "watermelon"] other_fruits = fruits fruits[0] = "bananas"
  1. We assigned fruits to ["apples", "oranges", "watermelon"]
  2. We assigned other_fruits to fruits
  3. Then we changed the first index of fruits from apples to bananas

What can we expect in this case?

print(fruits) print(other_fruits)

>> ['bananas', 'oranges', 'watermelon']

>> ['bananas', 'oranges', 'watermelon']

B‍oth fruits and other_fruits had the first index modified. This is unlike what happened to strings in the previous examples.

Why does this happen?

‍When assigning fruits to other_fruits, both variables point to the same reference in memory. Modifying both fruits or other_fruits would result in changes in both declarations. This is a common behaviour with mutable data types.

Mutable

This should also explain the example with strings. When we first assigned other_name to name, both variables did indeed point to the same reference in memory. However since strings are immutable, once we changed name, the variable now refers to a different reference Jane, while other_name still refers to the same reference that holds the value John.

Immutable

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.