Python Internals - Mutable vs Immutable Objects

 Understanding Python internals is crucial for writing bug-free code and is a favorite topic in technical interviews. On Day 1, we focus on how Python handles objects in memory, mutability, function arguments, and object identity.

Let’s break it down step by step.


1. Mutable vs Immutable Objects in Python

In Python, everything is an object, and each object is either mutable or immutable.

1a. Immutable Objects

Immutable objects cannot be changed after creation.

Examples:

  • int

  • float

  • str

  • tuple and

  • frozenset

Example:
Input
  • a = 10
  • b = a
  • b += 1
  • print(a)

Output - 10

🧠 This is because int is immutable.
When b += 1 is executed, Python creates a new object for b.
a still points to the original value 10.

1b. Mutable Objects

Mutable objects can be modified in place.

Examples:

  • list

  • dict

  • set and 

  • Most Custom Objects

Example:
Input
  • a = [1, 2, 3]
  • b = a
  • b.append(4)
  • print(a)
  • Output
Output - [1, 2, 3, 4]
🧠 This is because lists are mutable.

Both a and b reference the same object in memory, so modifying one affects the other. 

 

 

Comments

Popular posts from this blog

What Is a Design Pattern and Why Should We Use It?

Distributed Version Control System - Part 1

Distributed Version Control System - Part 2