Difference Between Mutable and Immutable Data Types in Python With Examples

 

 What Does Mutable vs Immutable Mean?

In Python, mutable objects can be changed after creation, while immutable objects cannot be changed once created.

 Definition

Term Meaning
Mutable Can be changed in-place (content editable)
Immutable Cannot be changed in-place (content fixed)

 Immutable Data Types

These types cannot be modified once assigned:

  • int
  • float
  • bool
  • str
  • tuple
  • frozenset
  • bytes

 Example:

x = "hello"
x[0] = "H"  #  Error: 'str' object does not support item assignment

 Mutable Data Types

These types can be changed after creation:

  • list
  • dict
  • set
  • bytearray
  • custom class (depending on implementation)

 Example:

my_list = [1, 2, 3]
my_list[0] = 100  #  Works
print(my_list)    # Output: [100, 2, 3]

 Why Does It Matter?

 Mutable:

  • Efficient when frequent changes are needed
  • Useful for caching, collections, etc.
  • Can have side effects if shared

 Immutable:

  • Safer to use in multithreading
  • Hashable (can be used as keys in dict or elements in set)
  • Encourages pure function design

 Identity vs Value Example

a = [1, 2, 3]       # Mutable
b = a
b.append(4)
print(a)            # Output: [1, 2, 3, 4] – a is also affected
x = "hello"         # Immutable
y = x
y = y + " world"
print(x)            # Output: "hello" – original not affected

 Check with id():

x = "hello"
print(id(x))
x += " world"
print(id(x))  # New object created → different id

 Summary Table

Feature Mutable Immutable
Can be changed  Yes  No
Examples list, dict, set int, str, tuple
Hashable  No (most)  Yes
Memory efficiency Less (object reused) More (new object each time)
Safer for sharing  No  Yes

 When to Use What?

  • Use immutable for constants, dictionary keys, and safe shared data.
  • Use mutable for collections that need modification (e.g., growing lists).

0 Comments:

Post a Comment