Memory and Identity in Python

In Python, everything is an object, and every variable is simply a reference (or label) that points to an object stored somewhere in memory.
When you assign a value to a variable, Python doesn’t just store that value — it creates an object in memory and makes your variable refer to it.
1. Variable References
Think of a variable like a name tag you stick onto a box. The box (object) lives in memory, and the name (variable) points to it.
For example:
x = [1, 2, 3]
Here’s what happens behind the scenes:
- A list object [1, 2, 3] is created in memory.
- The variable x points to (references) that list.
If you then assign::
y = x
You’re not creating a new list — you’re simply making y
point to the same object in memory that x
points to.
2. Checking Object Identity with id()
# Two variables pointing to the same object
x = [1, 2, 3]
y = x # y references the SAME list as x
print("x id:", id(x))
print("y id:", id(y))
print("Same object?", x is y)
Output:
x id: 1679998307072
y id: 1679998307072
Same object? True
What This Shows
id(x)
returns a unique number representing the object’s memory location.is
checks if both variables point to the same memory address.- Since
y = x
, both variables share the sameid
.
3. Identity vs. Equality
Let’s compare separate objects with the same content:
a = [1, 2, 3]
b = [1, 2, 3] # Different object, same content
print("a == b:", a == b) # True → Values are the same
print("a is b:", a is b) # False → Different memory locations
Output:
a == b: True
a is b: False
Key Difference:
==
checks if values are equal.is
checks if variables reference the exact same object in memory.
4. Memory Optimization with Immutable Objects
Python optimizes memory by reusing certain immutable objects like small integers, strings, and booleans.
Example:
x = 10
y = 10
print(x is y) # True → Small integers are cached
However, this optimization doesn’t always apply:
a = 1000
b = 1000
print(a is b) # Might be False → Large integers not always cached
Key Takeaways :
- Every Python variable points to an object in memory.
- Use
id()
to check an object’s identity (its memory reference). - Use
is
to test if variables reference the same object. - Use
==
to test if objects have equal values. - Python reuses small immutable objects (like small integers or short strings) for efficiency.
Tip:
When dealing with mutable types (lists, dictionaries, sets), be careful when assigning variables — changes to one variable may affect others if they share the same reference. Always create copies when you need independent objects.
Hope this tutorial was helpful!.
To continue building your skills, your next step is to learn about Python Loops in detail.