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 types?
Immutable Data Type
let's explore an example with the immutable data type string:
name = 'John' other_name = name name = 'Jane'
- We just assigned
name
toJohn
- then we assigned
other_name
toname
- then we changed the variable
name
toJane
What 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"
- We assigned
fruits
to["apples", "oranges", "watermelon"]
- We assigned
other_fruits
tofruits
- Then we changed the first index of
fruits
fromapples
tobananas
What can we expect in this case?
print(fruits)
print(other_fruits)
>> ['bananas', 'oranges', 'watermelon']
>> ['bananas', 'oranges', 'watermelon']
Both 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