Python Mutable vs. Immutable Data Types

Mutable and Immutable Data Types in Python

Mutable or immutable is the fancy word for explaining the property of data types of being able to get updated after being initialized. The basic explanation is thus: A mutable object is one whose internal state is changeable. On the contrary, once an immutable object in Python has been created, we cannot change it in any way.

What are Mutable Data Types?

Anything is said to be mutable when anything can be modified or changed. The term "mutable" in Python refers to an object's capacity to modify its values. These are frequently the things that hold a data collection.

What are Immutable Data Types?

Immutable refers to a state in which no change can occur over time. A Python object is referred to as immutable if we cannot change its value over time. The value of these Python objects is fixed once they are made.

List of Mutable and Immutable objects

Python mutable data types:

  • Lists
  • Dictionaries
  • Sets
  • User-Defined Classes (It depends on the user to define the characteristics of the classes)

Python immutable data types:

  • Numbers (Integer, Float, Complex, Decimal, Rational & Booleans)
  • Tuples
  • Strings
  • Frozen Sets

The Python id() Function

When you define a Python object, the program sets a memory section aside. Every Python object has a distinct address that informs the application where the item is located in memory.

Every object in Python has a distinct ID connected to the object's memory address. Use the built-in Python id() function to read the special ID.

Let's read the position of a sample string object in memory, for instance:

Code

Output:

140452604995952

Mutability in Python

As we have already told, an immutable Python object cannot be altered.

In Python, the integer data type is a prime case of an immutable object or data type. Let's conduct an easy experiment to understand this.

Let's first make two integer variables, x and y. The variable y is a reference to the variable x:

Now, x and y both point towards the same location in memory. In other words, both integer variables should have the same ID returned by the id() function. Let's confirm that this is true:

Code

Output:

x and y have same id:  True

As a result, the variables x and y points to a single integer object. In other words, even though there is just one integer variable, two variables refer to it.

Let us change x's value now. Next, let's compare the reference ids of x and y once more:

Code

Output:

x and y have the same ids: False

This is because x now points to a distinct integer object. Therefore, the integer variable 3 itself remained constant. However, the variable x that previously referred to it now directs users to the new integer entity 13.

Therefore, even though it appears like we modified the original integer variable, we didn't. In Python, the integer object is an immutable data type, meaning that an integer object cannot be changed once created.

Let's conduct a similar test once more using a mutable object.

Create a list, for instance, and put it in a second variable. Then, compare the reference IDs of the two lists. Let's then make some changes to the list we created. Then, let's see if the reference IDs of both lists still coincide:

Code

Output:

Both list variables have the same ids:  True
Both list variables have the same ids:  True

Furthermore, their reference IDs match. As a result, the list objects num and l point to the memory location. This demonstrates that we could explicitly change the list object by adding one more element. The list data structures must therefore be mutable. And Python lists operate in this way.

Example of Mutable Objects in Python

List

As a result of their mutable nature, lists can change their contents by incorporating the assignment operators or the indexing operators.

Let's look at an example of that.

Code

Output:

The original list:  ['Python', 'Java', 23, False, 5.3]
The modified list:  ['Python', 'Java', 'changed', False, 5.3]

Dictionary

Due to the mutability of dictionaries, we can modify them by implementing a built-in function update or using keys as an index.

Let's look at an illustration of that.

Code

Output:

The original dictionary:  {1: 'a', 2: 'b', 3: 'c'}
The modified dictionary:  {1: 'a', 2: 'changed', 3: 'c'}

Set

Due to the mutability of sets, we can modify them using a built-in function (update).

See an illustration of that:

Code

Output:

The original set:  {1, 2, 3, 4}
The modified set:  {1, 2, 3, 4, 'b', 'a', 'c'}

Example of Immutable Python Objects

int

Since int in Python is an immutable data type, we cannot change or update it.

As we previously learned, immutable objects shift their memory address whenever they are updated.

Here is an illustration of that:

Code

Output:

The memory address of int before updating:  11531680
The memory address of int after updating:  11532000

float

Since the float object in Python is an immutable data type, we cannot alter or update it. As we previously learned, immutable objects shift their memory address whenever they are updated.

Here is an illustration of that:

Code

Output:

The memory address of float before updating:  139992739659504
The memory address of float after updating:  139992740128048

String

Since strings in Python are immutable data structures, we cannot add or edit any data. We encountered warnings stating that strings are not changeable when modifying any section of the string.

Here is an illustration of that:

Code

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-3-4e0fff91061f> in <module>
      3 string = 'hello peeps'
      4 
----> 5 string[0] = 'X'
      6 
      7 print(string)

TypeError: 'str' object does not support item assignment

Tuple

Because tuples in Python are immutable by nature, we are unable to add or modify any of their contents. Here is an illustration of that:

Code

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-e011ebc4971e> in <module>
      5 
      6 # Trying to modify the tuple object
----> 7 tuple_[0] = 'X'
      8 print(tulple_)
      9 

TypeError: 'tuple' object does not support item assignment

FrozenSet

Like sets, frozensets are immutable data structures. While the set's components can always be changed, this cannot be done with a frozenset. Therefore, nothing can be added to or updated in the frozenSet.

Here is an illustration of that:

Code

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-2cafcda94faf> in <module>
      6 
      7 # Updating the value of the frozenset
----> 8 fset[1] = 76
      9 print(fset)
     10 

TypeError: 'frozenset' object does not support item assignment





Latest Courses