In Python, what does “Immutable” mean?

In Python, when every entity is an object, what does immutable mean? Python, unlike some other programming languages, does not require you to explicitly specify the type of data you’re assigning to a variable. Instead, it assigns the data type automatically based on the value you specify.

In summary, each variable contains an object instance and is assigned a unique object ID generated during program execution. The Object ID is an integer that represents the memory location where the variable’s value is stored.

To obtain the ID of each object, open Python Shell and invoke the default id() function, passing the variable name as a parameter.

Example:

# Give the string as static input and store it in a variable.
# (variable Initialization)
gvn_str = "welcome to Pyton-programs"
# Invoke the id() function, by passing the variable name(given string) as
# an argument.
# Store it in a variable.
rslt_id = id(gvn_str)
# Print the given string's Object id.
print("The given string's object Id = ", rslt_id)

Output:

The given string's Object id =  139677158260784

Mutable and Immutable Objects

In Python, each variable holds an instance of an object. In Python, there are two types of objects: mutable objects and immutable objects. When an object is created, it is given a unique object id. The type of the object is determined at runtime and cannot be modified later. Conversely, if it is a mutable object, its state can be modified.

To summarise the differences, mutable objects can change their state or content, but immutable objects cannot.

Immutable Objects: These are built-in types such as int, float, boolean, string, unicode, and tuple. In other words, an immutable object cannot be modified once it has been created.

For Tuples:

Example

# Give the string as static input and store it in a variable.
gvn_tupl = (5, 3, 1, 8)
# Print the tuple before modification.
print(gvn_tupl)
# Modidify the element present at the zeroth index to 10
gvn_tupl[0] = 10
# Print the tuple after modification.
print(gvn_tupl)

Output:

Traceback (most recent call last):
  File "/home/3ca1ca5cd18ba9417154eab3aa732be9.py", line 6, in <module>
    gvn_tupl[0] = 10
TypeError: 'tuple' object does not support item assignment

Explanation:

Here we get an error beacuase, tuple is immutable. That means we cannot 
change the values of it once it is created.

For Integers

Approach:

  • Give the number as static input and store it in a variable.
  • Get the ID of the given number by passing it as an argument to the id() function.
  • Store it in another variable.
  • Modify/change the given number with some other random number and store it in the same variable.
  • Get the ID of the modified number by passing it as an argument to the id() function.
  • Store it in another variable.
  • Check if the ID if the given number is the same before and after modification using the if conditional statement.
  • If it is True, then print “The Id if the given number is same before and after modification.
  • Else print “The Id if the given number is NOT same before and after modification”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 50
# Get the ID of the given number by passing it as an argument to the id() function.
# Store it in another variable.
orignl_id = id(gvn_numb)
# Modify/change the given number with some other random number and
# store it in the same variable.
gvn_numb = 100
# Get the ID of the modified number by passing it as an argument to the
# id() function.
# Store it in another variable.
chngd_id = id(gvn_numb)
# Check if the ID if the given number is the same before and after modification
# using the if conditional statement.
if orignl_id == chngd_id:
    # If it is True, then print "The Id of the given number is same before
        # and after modification.
    print("The Id of the given number is same before and after modification")
else:
    # Else print "The Id of the given number is NOT same before and after modification".
    print("The Id of the given number is NOT same before and after modification")

Output:

The Id of the given number is NOT same before and after modification

Mutable Objects:

Mutable objects can be modified or changed even after they are created. we can change the values of it once it is created.

Examples of mutable objects in python are List, Dictionaries, and Sets. Custom classes are mutable in general.

The memory location or list ID stayed constant although the values changed. That is, Python allocated more memory space to the location in order to consider the new values.

This means that a list is a “mutable” or “changeable” object.

Approach:

  • Give the list as static input and store it in a variable.
  • Print the given list before modification.
  • Modify the element present at the zeroth index of the given list to “hello”.
  • Print the given list after modification.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["welcome", "to", "python", "programs"]
# Print the given list before modification.
print("The given list before Modification: ")
print(gvn_lst)
print()
# Modify the element present at the zeroth index of given list to "hello"
gvn_lst[0] = "hello"
# Print the given list after modification.
print("The given list after Modification: ")
print(gvn_lst)

Output:

The given list before Modification: 
['welcome', 'to', 'python', 'programs']

The given list after Modification: 
['hello', 'to', 'python', 'programs']

Brief Recap

Python handles mutable and immutable objects differently. Immutable objects are easier to access and more expensive to change because they necessitate the generation of a duplicate.
Mutable things, on the other hand, are easily changed.
When it is necessary to change the size or content of an object, it is best to use changeable objects.

Exception: However, there is an exception in the case of immutability. In Python, we know that a tuple is immutable. However, the tuple is made up of a sequence of names with fixed bindings to objects.

Let us consider a tuple

 gvn_tup = ([3, 4, 5], 'names')

The tuple is made up of a string and a list. Because strings are immutable, we cannot change their value. However, the list’s contents are subject to change. The tuple itself is not mutable, but it contains mutable objects.

As a general rule, Generally, Primitive-like types are almost certainly immutable, whereas Customized Container-like types are typically mutable.

Immutable Objects have the advantage of being significantly faster to access than the mutable counterparts.