A data type has the property Mutable or Immutable. This means that some data types can change after creation, while others cannot change.
Data types can be either mutable or immutable and this basically means that:
Each variable has a so called memory address, which is a way for the computer to store data for later access.
Some examples of data types that are mutable are:
and some examples of data types that are immutable are:
For example, if we define an int, which is an immutable data type:
a = 10
And then printing the memory adress
The variable has the memory adress
If we then define another variable with the same value, this variable will get the same memory address:
b = 10 print(hex(id(b)))
Since these variables are Immutable the adress cannot be changed, which means that if we change the value of the variable, the address will also change:
a = 12 print(hex(id(a)))
Resulting in a new memory adress
However, this will not be the same for a mutable data type. Take, for example, lists that are mutable:
a = [1, 2, 3, 4, 5] b = a; print(hex(id(a))) print(hex(id(b)))
In this case, a and b share the same memory address. This means that if the value changes in a, the value will also change in b:
a = 10 print(a) print(b) print(hex(id(a))) print(hex(id(b)))
And the result is:
[1, 2, 3, 10, 5] [1, 2, 3, 10, 5] 0x10ffcc4c8 0x10ffcc4c8
Since a and b share the same memory address, it means that if the value changes in a, it will also change in b!
Note that the memory address is the same as before the change for the mutable data types.