---Advertisement---

 Mutable vs Immutable Objects in Python: A Comprehensive Guide with Examples 2025

By Bhavani

Updated On:

---Advertisement---
Mutable vs Immutable Objects in Python

👉 Mutable vs Immutable Objects in Python with Examples

Mutable vs Immutable Objects in Python : Python objects are broadly categorized into two types: Mutable and Immutable. Understanding their differences is crucial for effective coding and memory management in Python.

👉What is a Mutable Object?

A mutable object in Python can change its state or content after creation. These objects are generally used to store collections of data and allow modification over time.

👉Examples of Mutable Objects:

  • Lists
  • Dictionaries
  • Sets

👉Example Code for Mutable Objects:

mut_list = [1, 2, 3]

print(“Original list:”, mut_list)

mut_list[0] = ‘Python’

print(“Modified list:”, mut_list)

👉Output:

Original list: [1, 2, 3]

Modified list: [‘Python’, 2, 3]

Here, the original list changed without creating a new object.

👉ID Example for Mutable Objects:

mut_list = [1, 2, 3]

print(“ID before change:”, id(mut_list))

mut_list[0] = ‘Python’

print(“ID after change:”, id(mut_list))

👉Output:

ID before change: 140232556028800

ID after change: 140232556028800

The ID remains the same, indicating that the same object is modified.

👉What is an Immutable Object?

An immutable object cannot change its state or content once created. Any modification results in the creation of a new object.

👉Examples of Immutable Objects:

  • Integers
  • Strings
  • Tuples
  • Frozen Sets

👉Example Code for Immutable Objects:

a = 100

print(“ID before change:”, id(a))

a = 200

print(“ID after change:”, id(a))

👉Output:

ID before change: 9796256

ID after change: 9799456

Here, Python creates a new object instead of modifying the original.

👉Mutable vs Immutable Objects: Key Differences

AspectMutable ObjectImmutable Object
ChangeableYesNo
Thread SafetyNot thread-safeThread-safe
Memory EfficiencyMay consume more memoryEfficient memory usage
ExamplesLists, Dictionaries, SetsIntegers, Strings, Tuples, Frozen Sets

👉Mutable vs Immutable Objects in Python Dictionary Key Rules in Python

In Python, dictionary keys must be immutable. Attempting to use a mutable object as a key will result in an error:

a = [1, 2, 3]

dict_example = {a: ‘value’}  # Raises TypeError: unhashable type: ‘list’

👉Exceptions in Immutability

Mutable vs Immutable Objects in Python : Python allows some exceptions where immutable objects can contain mutable elements. For example, tuples can contain mutable objects:

tuple_example = ([1, 2], ‘Immutable’)

print(“Before change:”, tuple_example)

tuple_example[0][0] = ‘Changed’

print(“After change:”, tuple_example)

👉Output:

Before change: ([1, 2], ‘Immutable’)

After change: ([‘Changed’, 2], ‘Immutable’)

Here, the tuple remains immutable, but the mutable list inside it gets modified.

Polymorphism in Python with Examples

Download Python

Leave a Comment

Index