Python Datatypes – Immutable & Mutable

Python Immutable

  • Value of Immutable data types cannot be changed once they are created.
  • When an object gets created, it is assigned a unique object id.

Python Object

Every Python object has some key elements that make its structure.

  • ID(Identity)
  • Type
  • Value

age = 62

  • print(id(age))
  • print(type(age))
  • print(age)

Number

number = 42
print(id(number))

number += 1
print(id(number))

1657696608 #Output1
1657696640 #output2

String​

text = "Python Course"
print(id(text))


text += " with Reviving India"
print(id(text))


Output->

1565809038896
1565805802384

Want to modify string?

Below example shows what happens if one tries to modify string:

message = “Python Course“

Print(message[0])    #’P’

message[0] = 'p'

print(message)

Output :TypeError: ‘str’ object does not support item assignment

Tuple​

x= (10, 20, 30)

print(x)           #(10, 20, 30)

Print(type(x)) #Class

X[0] = 40

print(x) #Error

Output :Traceback (most recent call last):
  File "test.py", line 3, in < module >
    x[0] = 40
TypeError: 'tuple' object does not support item assignment

Points to Remember​

  • Concatenating string in loops wastes memory, as strings are immutable, concatenating two strings creates a 3rd string.
  • When using multiple iterations and building a large string, a lot of memory is wasted in creating and discarding objects. 
  • Immutable are quicker to access
  • Immutable objects are expensive to “change”, as it means creating a copy.
  • If an Immutable object contains only immutable objects, we cannot change their value

Mutable Datatype

  • Value of Mutable data types can be changed post creation.
  • MUD operations can be performed on Mutable objects
  • Mutable Object iterations can be coupled with MUD

List​

values = [4, 5, 6]
values = [4, 5, 6]

values2 = values

print(id(values))
print(id(values2))

Values[0]=8

print(values)   #[8, 5, 6]
print(values2)  #[8, 5, 6]

Output :

Id-2450343166664

Id-2450343166664

Tuple with List​

skills = ["Programming", "Machine Learning", "Statistics"]

person = (129392130, skills)
print(type(person))

print(person)
skills[2] = "Maths"
print(person)

Points to Remember​

  • Mutable objects are cheap as can be altered easily

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *