Immutable classification – Number, String and Tuples

  • 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<Tuple>

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

Few More Example

unique_identifier = 42
age = 24
skills = ("Python", "pandas", "scikit-learn")
info = (unique_identifier, age, skills)
print(id(unique_identifier))
print(id(age))
print(info)
print(id(info))

unique_identifier = 50
age += 1
skills += ("machine learning", "deep learning")
info = (unique_identifier, age, skills)
print(id(unique_identifier))
print(id(age))
print(info)
print(id(info))

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

0 Comments

Leave a Reply

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