πŸ”„ Python Tutorial β€” Mutable vs Immutable Types

Introduction 🌟

In Python, every value is stored as an object. These objects fall under two important categories:

  • πŸ”Ή Mutable β†’ can be changed after creation
  • πŸ”Ή Immutable β†’ cannot be changed once created

Understanding mutability is crucial for writing bug-free, efficient Python code β€” especially when working with functions, loops, and data structures.

Note

πŸ’‘ Immutable objects create new memory on modification
πŸ’‘ Mutable objects change in place

1. Immutable Types 🧊

These objects cannot be changed after they're created.

  • βœ” int
  • βœ” float
  • βœ” bool
  • βœ” str
  • βœ” tuple
  • βœ” frozenset
  • βœ” bytes

Example: Immutable Integer

immutable_int.py

x = 10
print(id(x))

x += 1
print(id(x))   # Different ID β†’ new object

βœ” Changing an int creates a new object in memory.

Example: Immutable String

immutable_str.py

s = "hello"
print(id(s))

s += " world"
print(id(s))  # New object created

Note

⚠️ Strings cannot be modified β€” every change creates a new one.

2. Mutable Types πŸ”§

These objects can be modified in place without creating new objects.

  • βœ” list
  • βœ” dict
  • βœ” set
  • βœ” bytearray
  • βœ” custom class objects

Example: Mutable List

mutable_list.py

a = [1, 2, 3]
print(id(a))

a.append(4)
print(id(a))   # Same ID β†’ modified in place

βœ” List changed without creating a new object.

Example: Mutable Dictionary

mutable_dict.py

d = {"a": 1}
print(id(d))

d["b"] = 2
print(id(d))  # Same ID

3. Key Difference Visualization πŸ“Š

TypeChanges Allowed?Memory AllocationExamples
ImmutableNoCreates new objectint, float, str, tuple
MutableYesModifies existing objectlist, dict, set

4. Why Does Mutability Matter? 🧠

  • βœ” Helps avoid bugs caused by shared references
  • βœ” Affects performance & memory usage
  • βœ” Important when passing objects to functions
  • βœ” Crucial for understanding deep vs shallow copies

5. Mutability in Function Arguments πŸ“₯

Mutable objects can be modified inside a function, affecting the original value.

Mutable Example

func_mutable.py

def modify(lst):
    lst.append(100)

a = [1, 2, 3]
modify(a)
print(a)  # [1,2,3,100]

Immutable Example

func_immutable.py

def modify(x):
    x += 10

n = 5
modify(n)
print(n)  # Still 5

βœ” Integers (immutable) cannot be changed inside the function.

6. Tuple vs List β€” Common Interview Question πŸ”Ž

tuple_vs_list.py

t = (1, 2, 3)
l = [1, 2, 3]

# t[0] = 10   # ❌ Error
l[0] = 10     # βœ” Works

βœ” Tuples are immutable, lists are mutable.

7. Frozen Set β€” Immutable Version of Set ❄️

frozenset_example.py

s = frozenset([1, 2, 3])
# s.add(4)  # ❌ Error

8. Shared Reference Danger (Mutable) ⚠️

shared_reference.py

a = [1, 2, 3]
b = a   # both point to same object

b.append(99)
print(a)  # [1,2,3,99]

Note

⚠️ Assigning mutable objects doesn't copy them β€” both variables share the same object.

9. Best Practices πŸ’‘

  • βœ” Be careful when passing mutable objects to functions
  • βœ” Use immutable types for keys in dictionaries
  • βœ” Prefer immutable types when shared across threads
  • βœ” Use copy() or deepcopy() to avoid shared references

10. Cheat Sheet πŸ“˜

CategoryMutableImmutable
Numericβ€”int, float, complex
Sequencelisttuple, str
Set Typessetfrozenset
Mappingdictβ€”
Binarybytearraybytes

Conclusion πŸŽ‰

>>β€œMutable objects change themselves β€” immutable objects create new versions of themselves.” ✨

You now fully understand Mutable vs Immutable Types in Python! Want the next topic? Try Object Identity, Garbage Collection, Name Binding, or Memory Management. Just tell me! 😊