Everything in Python is an object. There are two types of objects in Python
- Mutable
- Immutable
Immutable objects are those whose value cannot be changed after their creation. A well-known example of this is a tuple.
Mutable objects: lists, sets, dictionaries
Immutable objects: Tuples, integers, floats, strings, frozen sets
Before going deep into this topic, we should know about the id() function in Python.
id() function in python:
This function returns the identity of an object. This is guaranteed to be unique and constant for an object. The id of an object is created when the object is created. See below for examples.
example1:
l=[1,2,3]
print(id(l))
Output:
2018064114312
example 2:
x= 10
print(id(x))
Output:
140736328131504
Ok, now let us see some examples of the functionality of mutable and immutable objects.
let us take an example of a list.
l=[1,2,3]
print(id(l))
l.append(5)
print(id(l))
Output:
2018059045576
2018059045576
Here, we can observe that as lists are mutable objects. We can change the value of lists without changing their id.
Now, if we take an example of a tuple, there is no chance of changing their value since it is an immutable object. If we take the example of int, string, which are also immutable, we can change the value of them, but changing their value creates a different id. See the below example.
example1:
x=10
print(id(x))
x=x+10
print(id(x))
Output:
140736328131504
140736328131824
example2:
s="string"
print(id(s))
s=s+"s"
print(id(s))
2018054115200
2018063371320
More on immutable objects:
We cannot change a tuple. But, if a tuple has an immutable object in it, we can change that immutable one in the tuple.
example:
t=(1, 2, [12,3])
t2.append(4)
print(t2)
Output:
(1, 2, [12,3,4])
FOR, VISUALISATION OF THIS CODE IN PYTHON IDLE SEE MY YOUTUBE VIDEO ABOUT THIS: https://youtu.be/tYq5ROASMvs
FOR LATEST UPDATES OF MY POSTS, SUBSCRIBE TO MY BLOG
FOR LATEST VIDEOS, SUBSCRIBE TO MY YOUTUBE CHANNEL: https://www.youtube.com/channel/UCPnw9O8cvhX9mS195imI8Sw
FOLLOW ME ON GITHUB: https://github.com/VallamkondaNeelima?tab=repositories
Comments
Post a Comment