Mutable vs Immutable Objects in Python


Everything in Python is an object. Every variable in python holds an instance of an object.There are two types of objects in python i.e. Mutable and Immutable objects.

Since everything in Python is an Object, every variable holds an object instance. When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable. Simple put, a mutable object can be changed after it is created, and an immutable object can’t.

Immutable Objects :

Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. In simple words, an immutable object can’t be changed after it is created.

Mutable Objects :

list, dict, set, byte array are mutable objects.

Let us do a practical example to find out the mutability of object type

#create two variables
x = 10
y = a

We are creating an object of type int. identifiers x and y points to the same object.

To check that both x and y are pointing to the same object, check the id of x and y

x = 10
y = x
print("id of x =",id(x))
print("id of y =",id(y))
OUTPUT
id of x = 1579869088
id of y = 1579869088

if we do a simple operation.


x = x + 1
         

Now check the id of x and y, and print the value of both variables

x = 10
y = x
print("before make changes into x\n")
print("id of x =",id(x))
print("id of y =",id(y))

print("Value of x =",x)
print("Value of y =",y)

x = x + 1
print("\nafter make changes into x\n")
print("id of x =",id(x))
print("id of y =",id(y))

print("Value of x =",x)
print("Value of y =",y)
OUTPUT
before make changes into x

id of x = 1579869088
id of y = 1579869088
Value of x = 10
Value of y = 10

after make changes into x

id of x = 1579869104  id of x gets change
id of y = 1579869088  id of y remain same
Value of x = 11
Value of y = 10

The object in which x was tagged is changed. object 10 was never modified. Immutable objects doesn’t allow modification after creation

Example 1:

File Name: Test.py
# Python code to test that 
# tuples are immutable 
	
tuple1 = (0, 1, 2, 3) 
tuple1[0] = 4
print(tuple1)
OUTPUT: Error
Traceback (most recent call last):
  File "C:/Python36/Test.py", line 5, in 
    tuple1[0] = 4
TypeError: 'tuple' object does not support item assignment

Example 2:

File Name: Test.py
# Python code to test that 
# strings are immutable 

message = "Welcome to ProwessApps"
message[0] = 'p'
print(message) 

OUTPUT: Error
Traceback (most recent call last):
  File "C:/Python36/Test.py", line 5, in 
    message[0] = 'p'
TypeError: 'str' object does not support item assignment

In the case of mutable objects

# Python code to test that 
# lists are mutable 

l = [1,2,3,4]
k = l

We are creating an object of type list. identifiers l and k tagged to the same list object, which is a collection of 4 immutable int objects.


id(l) == id(k)
       

Now poping an item from list object does change the object,


l.pop()                    
                

object id will not be changed


id(l) == id(k)
       

l and k will be pointing to the same list object after the modification. The list object will now contain [1, 2, 3].


So what have we seen and learn so far from the above examples?

  • Python handles mutable and immutable objects differently.

  • Immutable are quicker to access than mutable objects.

  • Mutable objects are great to use when you need to change the size of the object, example list, dict etc.. Immutables are used when you need to ensure that the object you made will always stay the same.

  • Immutable objects are fundamentally expensive to “change”, because doing so involves creating a copy. Changing mutable objects is cheap.

Exception case

However, there is an exception in immutability as well. We know that tuple in python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects. Consider a tuple

Consider a tuple


tup = ([1,2,3,4], 'prowessapps') 
                

The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.


Next chapter is built-in functions in python





 







Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved