Python's Memory Model: Objects, References & Identity
After this lesson, you will be able to:
- Understand that everything in Python is an object with a type, id, and value
- Distinguish between variables as references (labels) versus value containers
- Use id() to inspect memory addresses and understand object identity
- Correctly use 'is' for identity and '==' for equality
- Explain mutable vs immutable types and why it matters
- Notice that Python sometimes reuses the same object for small numbers (a handy optimization)
- Perform shallow copies and deep copies using the copy module
Before you start
#Everything in Python is an Object
Relax! This lesson covers a concept that confuses even experienced developers. Take your time. Understanding this deeply will save you hours of debugging later.
int x = 42 stores the value directly in memory. Python is different. Every value is a full object with three properties: a type, an identity (memory address), and a value.# Every value has a type
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type([1, 2, 3])) # <class 'list'>
print(type(None)) # <class 'NoneType'># Every object has a unique identity (memory address)
x = 42
print(type(x)) # <class 'int'>
print(id(x)) # e.g., 140234567 (unique address)
print(x) # 42 (the value)#Variables Are References, Not Boxes
This is the most important concept in Python's memory model. Variables do not contain values. They point to objects.
a = [1, 2, 3]
b = a # b points to the SAME list object
b.append(4)
print(a) # [1, 2, 3, 4] -- a changed too!
print(b) # [1, 2, 3, 4]
print(a is b) # True -- same object in memoryStep through it visually. Below is an animated names region (left) and heap (right). Watch the green binding arrow form when you sayx = 5, watch a second arrow appear (pointing at the SAME object!) when you sayy = x, then watch the arrow MOVE when you rebindx. Preset D shows the mutation case, and preset E shows the augmented-assignment trap where you accidentally create a new list.
See it happen! Use the step-through debugger below. Click Run, then Step Forward to watch each line execute and see variables change in real time.
What does this print? x = [1,2]; y = x; y = [3,4]; print(x)
y = [3, 4]) peels the label "y" off the old list and sticks it on a new list. The old list [1, 2] still exists with "x" pointing to it.#Now trace it yourself
a and b become two labels on the same list. Mutating through a makes b "see" the change, and a is b is True, because they point to one object, not two.Edit the code, then click Trace it. Python actually runs in your browser — every line, every variable, every print.
Click Trace it to capture the execution trace. The scrubber below will let you step through every variable change line-by-line.
#Identity vs Equality
Python has two ways to compare:
==checks equality. Do they have the same value?ischecks identity. Are they the exact same object in memory?
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # True -- same value
print(x is y) # False -- different objects!
print(id(x)) # e.g., 140234567
print(id(y)) # e.g., 140234999 (different address)
z = x
print(x is z) # True -- z is an alias for xa and b each get their own list object, so == is true and is is false. Then c = a adds a second label to one object, and now both are true.#Mutable vs Immutable Types
# Immutable: int, str, tuple, float, bool
s = "hello"
# s[0] = "H" # TypeError! Strings are immutable.
s = "Hello" # Creates a NEW string object. Old "hello" is abandoned.
# Mutable: list, dict, set
lst = [1, 2, 3]
lst.append(4) # Modifies the SAME object in place.
print(lst) # [1, 2, 3, 4]#Integer Caching
42 points to the same object.# Small integers are cached
a = 100
b = 100
print(a is b) # True -- same cached object
# Large integers are NOT part of the small-int cache. But equal literals in the
# same code object (a module, or one function body) are deduplicated by the
# compiler, so this still prints True:
a = 1000
b = 1000
print(a is b) # True -- one shared constant, not the small-int cache
# Build them at runtime instead and the objects really are distinct:
a = int("1000")
b = int("1000")
print(a is b) # False -- different objects
print(a == b) # True -- same value==. How the cache and string interning work inside the interpreter is in the optional lesson on Python internals.a = int('256'); b = int('256'); print(a is b) then a = int('257'); b = int('257'); print(a is b)
Good news: You NEVER need to memorize which numbers are cached. Just remember: always use==for comparing values andisonly forNone. That's it!
#Reference Counting
Python uses reference counting to manage memory. Each object tracks how many variables point to it. When the count reaches zero, the memory is freed.
import sys
a = [1, 2, 3]
print(sys.getrefcount(a)) # 2 (a + the argument to getrefcount)
b = a
print(sys.getrefcount(a)) # 3 (a + b + the argument)
del b
print(sys.getrefcount(a)) # 2 (back to a + the argument)gc module, is in the optional lesson on Python internals. For everyday code, the rule above is enough: when the last name goes away, the object goes away.#None, True, False Are Singletons
None object, ONE True object, and ONE False object in the entire Python process.x = None
y = None
print(x is y) # True -- same singleton object
print(id(None)) # one fixed address for the entire process
# This is why 'is' is correct for None checks
result = None
if result is None:
print("No result") # Correct and Pythonic#Shallow Copy vs Deep Copy
import copy
original = [1, 2, [3, 4], [5, 6]]
# ALIAS -- NOT a copy
alias = original
alias.append(99)
print(original) # [1, 2, [3, 4], [5, 6], 99] -- changed!
# Reset
original = [1, 2, [3, 4], [5, 6]]
# SHALLOW COPY -- new outer list, inner objects shared
shallow = original.copy()
shallow.append(99)
print(original) # [1, 2, [3, 4], [5, 6]] -- outer unaffected
shallow[2].append(99)
print(original) # [1, 2, [3, 4, 99], [5, 6]] -- inner changed!
# Reset
original = [1, 2, [3, 4], [5, 6]]
# DEEP COPY -- completely independent at every level
deep = copy.deepcopy(original)
deep[2].append(99)
print(original) # [1, 2, [3, 4], [5, 6]] -- completely unaffected`a = [[1,2],[3,4]]`. You write `b = a.copy()` then `b[0].append(99)`. What does `print(a)` show?
#Code Playground
Tests: Run the code. Try the solution for bonus challenges.
#Key Takeaways
- Everything in Python is an object with a type, an id, and a value
- Variables are references, not boxes — assignment creates a label, not a copy
ischecks identity (same object),==checks equality (same value) — useisonly for None/True/False- Immutable types cannot be changed in place — every modification creates a new object
- CPython caches integers -5 to 256 — never rely on
isfor value comparisons - Reference counting frees objects when no references remain
- Shallow copy shares inner objects; deep copy is fully independent
a = [1, 2, 3]; b = a; b.append(4); print(len(a))