Memory and Identity in Python

Memory and Identity in Python
Lesson 18: 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 now do this:

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.

Example: 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’s Happening Here

  • id(x) gives you a unique number representing the object’s location in memory.
  • x is y checks whether both variables point to the same memory address (same object).
  • Since y = x, both variables share the same id.

🧩 Different Objects with the Same Value

Now let’s compare this with separate lists that happen to have the same contents:

a = [1, 2, 3]
b = [1, 2, 3]

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
  • == checks if the values are equal.
  • is checks if both variables refer to the exact same object in memory.

⚙️ Memory Reuse for 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

But with larger or more complex objects, that may not happen:

a = 1000
b = 1000
print(a is b)   # Might be False → Large integers not always cached

Key Takeaways

  • Every variable in Python points to an object in memory.
  • Use id() to check an object’s identity (its memory reference).
  • Use is to test if two variables reference the same object.
  • Use == to test if two objects have equal values.
  • Python reuses small immutable objects (like small integers or short strings) for efficiency.

Tip:

When dealing with mutable types (lists, sets, dicts), be careful when assigning variables — changes in one variable may affect another if they share the same reference.