Mutable and Immutable Data Types in Python

A data type has the property Mutable or Immutable. This means that some data types can change after creation, while others cannot change.

WHAT DOES IT MEAN THAT A DATA TYPE IS MUTABLE OR IMMUTABLE?

Data types can be either mutable or immutable and this basically means that:

  • Mutable data type is possible to change after it has been created
  • Immutable data type cannot be changed.

 

Each variable has a so called memory address, which is a way for the computer to store data for later access.

 

 

Mutable data type is possible to change after it has been created, and Immutable data type cannot be changed

 

 

Some examples of data types that are mutable are:

  • Sets
  • Array / Lists
  • Dictionaries

 

and some examples of data types that are immutable are:

  • Int
  • Booleans
  • String
  • Tuple
  • Float

Example on Mutable and Immutable Data types

For example, if we define an int, which is an immutable data type:

 

a = 10

And then printing the memory adress

 

print(hex(id(a)))

The variable has the memory adress

 

0x10daa2680

 

If we then define another variable with the same value, this variable will get the same memory address:

 

b = 10
print(hex(id(b)))

Resulting in

 

0x10daa2680

 

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

 

0x10daa26c0

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)))

Resulting in

 

0x10ffcc4c8
0x10ffcc4c8

 

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

For more information about Mutable and Immutable in Python we recommend the Python Docs website