One-Sentence Definition
Python names bind to objects: assignment normally changes a name binding rather than copying an object, so when multiple names reference the same mutable object, in-place mutations made through one reference are visible through all the others.
Why It Matters
- Root cause of a huge class of "mystery bugs": "I only modified
b—why didachange too?" Becauseaandbreference the exact same object in memory. - Understanding function argument passing: Python passes object references—a function can mutate a mutable object in place, but rebinding the parameter name inside the function does not rebind the caller's variable.
- Prerequisite for NumPy views, Pandas Copy-on-Write, and PyTorch shared-storage tensors (see k1.lib.numpy and k1.lib.pandas).
Boundaries & Caveats
A shallow copy creates a new outer container while keeping references to the original inner elements. copy.deepcopy recursively copies objects according to the copy protocol while preserving internal shared-reference structure; immutable objects, custom __deepcopy__ hooks, or external OS handles are not guaranteed to become completely independent copies.
How It Works / Diagram
From the Python Language Reference: "Objects are Python's abstraction for data... Every object has an identity, a type and a value"; the is operator compares object identity and id() returns it: https://docs.python.org/3/reference/datamodel.html#objects-values-and-types
| Operation | What Happens | Does It Affect the Original Object? |
|---|---|---|
b = a |
Binds a new name to the exact same object | They are the same object |
b.append(4) |
Mutates the object in place | Yes (visible via a as well) |
b = b + [4] |
Creates a new list and rebinds b to it |
No |
c = list(a) / a.copy() / copy.copy(a) |
Shallow copy: new outer container, inner elements still shared | Outer container unaffected; inner mutable elements remain shared |
copy.deepcopy(a) |
Recursively copies via the copy protocol | Subject to immutable objects, internal memoized sharing, and custom copy hooks |
== vs. is: == checks value equality, whereas is checks object identity (whether two references point to the exact same object). Always test for None using is None. PEP 8 recommends using is when comparing against singletons like None: https://peps.python.org/pep-0008/#programming-recommendations
Runnable Example
# File: examples/18_object_reference.py
# Variable = name (label), Object = value in memory. Assignment attaches a label rather than copying
a = [1, 2, 3]
b = a # b and a point to the exact same list object
b.append(4)
print("a =", a, "| a is b:", a is b, "| same id:", id(a) == id(b))
c = list(a) # New object (shallow copy)
print("c == a:", c == a, "| c is a:", c is a) # == compares value, is compares identity
# Rebinding vs. in-place mutation
x = 10
y = x
x = x + 1 # Creates a new int object and rebinds x to it
print("x, y =", x, y)
# Function arguments are passed by object reference
def add_item(lst): lst.append("new") # In-place mutation: visible to caller
def rebind(lst): lst = ["brand new"] # Local rebinding: invisible to caller
items = ["old"]
add_item(items); rebind(items)
print("items =", items)
# Reference count (CPython implementation detail)
import sys
obj = object()
print("Refcount (including temporary arg reference in getrefcount):", sys.getrefcount(obj))
alias = obj
print("After adding an alias:", sys.getrefcount(obj))
# Shallow copy vs. deep copy
import copy
nested = [[1, 2], [3]]
shallow, deep = copy.copy(nested), copy.deepcopy(nested)
nested[0].append(99)
print("Shallow copy affected:", shallow, "| Deep copy unaffected:", deep)
Recorded output (Python 3.15.0):
a = [1, 2, 3, 4] | a is b: True | same id: True
c == a: True | c is a: False
x, y = 11 10
items = ['old', 'new']
Refcount (including temporary arg reference in getrefcount): 2
After adding an alias: 3
Shallow copy affected: [[1, 2, 99], [3]] | Deep copy unaffected: [[1, 2], [3]]
Key takeaways:
- Inside
rebind,lst = [...]only rebinds the local parameter name to a new list, leaving the caller'sitemsuntouched; in contrast,add_itemcallsappendon the shared list object, which the caller sees immediately. - Because
shallowshares its inner lists withnested, mutatingnested[0].append(99)mutatesshallow[0]as well.
Common Pitfalls
- "Is Python pass-by-value or pass-by-reference?": Neither term captures it cleanly. The accurate term is call by object reference (or call by sharing).
- Using
isto compare numbers or strings:a is bmay evaluate toTruefor small integers or interned strings due to CPython caching, not a language guarantee. Since Python 3.8, comparing against literals withisemits aSyntaxWarning. - Assuming
.copy()performs a deep copy: Container.copy()methods perform shallow copies; usecopy.deepcopyfor nested structures. - Treating reference counts as part of the language specification:
sys.getrefcountis a CPython implementation detail, and the official docs note that returned values may not reflect true reference counts (for instance, immortal objects introduced in Python 3.12 report very large values): https://docs.python.org/3/library/sys.html#sys.getrefcount
Connection to AI Development
- NumPy basic slices are views while advanced indexing returns copies: Mutating a basic slice mutates the underlying array in place (see the final line of the example in k1.lib.numpy).
- PyTorch tensors:
b = aaliases the exact same tensor, anda.view(...)shares underlying storage; calla.clone()when you need an independent copy: https://docs.pytorch.org/docs/stable/tensor_view.html - Accidental sharing of config dictionaries: If multiple training runs share a single mutable
configdictionary and one run mutates the learning rate in place, subsequent runs inherit the mutated value. Usecopy.deepcopy(config)or immutable configs (such as frozen dataclasses). - Shared conversation history lists: Passing the same
messageslist to multiple concurrent agents that each call.append()cross-contaminates their prompt histories.
Further Reading
- Python Data Model: https://docs.python.org/3/reference/datamodel.html
- Ned Batchelder – Facts and myths about Python names and values (PyCon 2015): https://nedbatchelder.com/text/names1.html
- Python
copymodule documentation: https://docs.python.org/3/library/copy.html
Comprehension Check
Inside a function, what is the difference between executing items = [] and items.clear()?
Reference answer: items = [] rebinds the local parameter name to a new empty list, whereas items.clear() empties the existing list object in place, which is visible to the caller.
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 18_object_reference.py.
Companion Code & Verification Materials