Mutability vs. Immutability
Every variable in Python is a reference pointing to an object in memory. Objects are divided into two main categories:1. Mutable Objects
A mutable object can be changed after it is created. Examples include:- Lists (
list) - Dictionaries (
dict) - Sets (
set)
2. Immutable Objects
An immutable object cannot be changed after it is created. If you try to modify it, Python creates a new object at a new memory address. Examples include:- Integers (
int), Floats (float) - Strings (
str) - Tuples (
tuple) - Booleans (
bool)
Everything is an Object
In Python, everything is a first-class object. This includes integers, strings, functions, modules, and even classes themselves. An object in Python contains three things:- A Value: The data itself (e.g.,
"Hello"). - A Type: Defines what the object can do (e.g.,
<class 'str'>). - An Identity: A unique integer representing its memory address (retrieved via
id()).
Identity (id()) vs. Equality (==)
Understanding the difference between == and is is a common source of confusion:
- Equality (
==): Compares the values of the objects (uses the__eq__method). - Identity (
is): Compares the memory addresses of the objects (checks if both variables point to the exact same object in memory).
Reference Counting
Python manages memory automatically using garbage collection. The primary mechanism used is Reference Counting.- Every object in memory keeps track of how many variables are referencing it.
- When you assign an object to a variable, its reference count increases by 1.
- When a variable goes out of scope or is deleted, the reference count decreases by 1.
- When the reference count drops to 0, the object is destroyed, and the memory is reclaimed.
Practice & Exercises
To reinforce what you’ve learned in this section (Mutability, object types/identities, caching optimizations, and reference counting), practice with these interactive notebooks:Follow-Along Practice
Practice defining mutable and immutable objects, tracking id values, appending mutable sub-items inside tuples, comparing equal values vs identities, and tracking reference counts.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises on extending mutable lists, editing nested tuple elements, evaluating dictionary identities, and verifying small integer cache limits.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now that you understand Python’s internal memory structures, let’s learn how functions are treated as objects, closures, and writing custom decorators!Advanced Functions
Master lambdas, closures, and decorators