- What are an object’s identity, type and value in Python?
- What are the different types of mutable and immutable objects in Python?
- When to use mutable and immutable objects?
Every object in Python has an identity, a type and a value. The data in a Python programme/code is represented by objects or by relations between objects.
One may think of an object’s identity as its address in memory. Once an object is created, its identity never changes. We can extract the identity of an object using the built-in function
id() in Python, which returns an integer essentially. The
is operator is used to comapre identities of two objects.
The built-in function
type() returns the type of an object. Like identity of an object, it also never changes. It is defined when the object is created/at the runtime.
Unlike Identity and Value, the value of some objects can change. Objects whose value can change after their creation are called mutable objects whereas the objects whose value can not change after their creation are called immutable objects.
Some examples of Mutable Data Types in Python are list, dictionary and set.
#let us generate a list foo = [1,2,3,4] print(id(foo)) # let us add another element to the list and check its identity foo += [5,6] print(id(foo))
The identity of the list created does not change as Python updates the existing list rather than creating a new one.
Some examples of Immutable Data Types in Python are int, float, bool, string, tuple and range.
#let us generate a tuple bar = (1,2,3,4) print(id(bar)) # let us add another element to the list and check its id bar += (5,6) print(id(foo))
As you can see a new identity is generated as Python creates new tuple by merging the two.
Some objects such as list, dictionary and tuples contain references to other objects, such objects are containers.
The value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. When we talk about the mutability of a container, only the identities of the contained objects are implied, hence, the container is still considered immutable.
# let us create a tuple containing a list baz = ([1,2,3] , 6, 7) print(id(baz)) #let us add elements to the list inside the tuple baz.append(4) print(baz) print(id(baz))
139788464704560 ([1, 2, 3, 4], 6, 7) 139788464704560
As one can see, the container, the tuple created here is immutable but the list contained by it is mutable.
When to use what
One should apply immutability or use immutable objects when they want to guarantee that their value and their contents are not going to change. Also, they are quicker to access.
On the other hand, the use of mutable objects is recommended when there is a need to change the size or content of the object.