Python Mutable and Immutable data types

This blog Explains about python Mutable and Immutable data types.

Mutable vs Immutable Objects in Python. … Simple put, a mutable object can be changed after it is created, and an immutable object can’t. Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable.


Collections in Python are containers that are used to store collections of data, for example, list, dict, set, tuple etc. These are built-in collections.
Compound statements contain (groups of) other statements.

Mutable and Immutable Data Types in Python

  • Some of the mutable data types in Python are list, dictionary, set and user-defined classes.
  • On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range.

The == operator

Sometimes we don’t want to compare the identity of two objects, but to compare the values of these objects. We can do this using the == operator.

numbers=[1,2,3,4]
number2=[1,2,3]
print(numbers==number2)
False
print(numbers is number2)
False

  • All the data in a Python code is represented by objects or by relations between objects.
  • Every object has an identity, a type, and a value.
  • Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable.

Immutable data types => (float, integer, boolean, string, byte, complex)

Mutable data types => (list, set byte, array)

Compound data types => (list, set byte, array)

Example Programs:-

house_no=10
print(id(house_no))
house_no=18
print(id(house_no))

Output:-

1578039360
1578039488

Program 2:

house_no=10
print(id(house_no))
140727849392064
house_no=12
print(id(house_no))
140727849392128

Reference:

https://towardsdatascience.com/https-towardsdatascience-com-python-basics-mutable-vs-immutable-objects-829a0cb1530a