Object, Mutable and Immutable

In python everything is object. Objects have some property Identity, Type, and value.

Identity —> who is like its a coffee or a tea

Type —> whats the type like a herbal tea or a ginger tea.

value —> its have some value

tea_name = "lemon tea"

how_much_sugger = 2

# Identity of these two
print(f"ID of lemon tea: {id("lemon tea")}")  # OUTPUT: ID of lemon tea: 4386108144
print(f"ID of 2: {id(2)}")  # OUTPUT: ID of 2: 4383104816

# Type of these two
print(f" type of tea_name {type(tea_name)}")  # OUTPUT: type of tea_name <class 'str'>
print(f"type of how_much_sugger {type(how_much_sugger)}")  # OUTPUT: type of how_much_sugger <class 'int'>

# Value of these two
print(f"value of tea_name: {tea_name}")  # OUTPUT: value of tea_name: lemon tea
print(f"value of how_much_sugger: {how_much_sugger}")  # OUTPUT: value of how_much_sugger: 2

Mutable means that is changeable. Immutable means that is NOT changeable. we find the object is mutable or immutable with the help of the object identity Not with the value

Example of the Immutable: In this example as we see value is changing first we have the value of sugar_amount is 2 then it change to 12 and it changes. But in reality thats not happens.

sugar_amount = 2
print(f"First Initial sugar: {sugar_amount}")  # Output: First Initial sugar: 2

sugar_amount = 12
print(f"Second Initial sugar: {sugar_amount}")  # Output: Second Initial sugar: 12

print(f"ID of 2: {id(2)}")  # Output: ID of 2: 4376010944
print(f"ID of 12: {id(12)}")  # Output: ID of 12: 4376011264

As we can see in the diagram sugar_amount variable first pointing to the value “2“ then its pointing to the other value or we can say to another memory address of value “12“ . So this is Immutable.

Example of the Mutable: In this example we have spice_mix as you can see in the code snippet and diagram identity/ID is not change

spice_mix = set()
print(f"Initial spice mix id: {id(spice_mix)}")  # Output: Initial spice mix id: 4379026016
print(f"Initial spice mix id: {spice_mix}")  # Output: Initial spice mix id: set()

spice_mix.add("Ginger")
spice_mix.add("cardamom")
spice_mix.add("lemon")

print(f"Initial spice mix id: {spice_mix}")  # Output: Initial spice mix id: {'Ginger', 'lemon', 'cardamom'}
print(f"After spice mix id: {id(spice_mix)}")  # Output: After spice mix id: 4379026016

0
Subscribe to my newsletter

Read articles from Shubham Bhardwaj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shubham Bhardwaj
Shubham Bhardwaj