Python Object Aliasing & Shared State
Concrete strategies to detect when variables share mutable objects in Python, how to track aliases in trace tables, and clean production fixes.
See the About page for curation and verification details.
Aliasing is the quiet bug behind a huge share of code tracing errors and production incidents. Assignment in Python never copies data; it binds a name to an existing object. Two names pointing at one mutable object means a change made through either name is visible through both. This article shows how to see aliasing in a trace table using object IDs, demonstrates the classic surprises with verified outputs, covers the shallow-versus-deep copy distinction, and lists the defensive patterns that keep shared state from leaking across functions.
Names are tags, boxes are objects
The mental model: variables are sticky notes attached to objects, not containers holding values. Run this:
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b)
print(id(a) == id(b))Verified output on Python 3.12.10: [1, 2, 3, 4] True True
There is one list. Both names point at it. a is b tests identity (same object), not equality (same contents), and here both are trivially true because there is only one object in existence.
Representing aliasing in a trace table
Add an Object column with synthetic IDs. Every time an object is created, assign obj#1, obj#2, and so on. Bindings point at IDs; mutations edit the object row, not the variable rows.
- a = [1, 2, 3] creates obj#1, a points at obj#1. - b = a makes b point at obj#1 too. No new object exists. - b.append(4) mutates obj#1 to [1, 2, 3, 4]. Both a and b now display that list, because they were always displaying the same thing. learners who skip the object column accidentally treat b = a as a copy and predict a printing [1, 2, 3]. That single modeling mistake is the most common wrong answer in aliasing questions.
Aliasing through function arguments
Passing a list into a function passes the reference, so in-place changes reach the caller:
def append_bad(items):
items.append('injected')
original = ['safe']
append_bad(original)
print(original)Verified output: ['safe', 'injected']
Now compare rebinding, which breaks the link for the callee only:
def append_ok(items):
items = items + ['new'] # creates obj#2, local name moves to it
return items
original = ['safe']
result = append_ok(original)
print(original, result)Verified output: ['safe'] ['safe', 'new']
The plus operator built a fresh list; original never saw it. Same-looking functions, opposite sharing behavior. The difference is mutation versus creating a new object, and it is exactly what senior engineers are testing.
Shallow copy stops half the damage
list(), slicing [:], and copy.copy all make a new outer container but reuse inner objects:
import copy
data = [1, 2, [3, 4]]
shallow = copy.copy(data)
shallow[2].append(99)
print(data)Verified output: [1, 2, [3, 4, 99]]
The outer list is independent, the nested list is shared. For full isolation use deepcopy:
deep = copy.deepcopy(data)
deep[2].append(100)
print(data, deep[2])Verified output: [1, 2, [3, 4, 99]] [3, 4, 99, 100]
deepcopy rebuilt the inner list too, so data stayed put. Cost warning: deepcopy is much slower than shallow copying and must handle cycles, so reach for it deliberately, not reflexively.
Tuple gotcha: immutable container, mutable member
A tuple cannot be reassigned, but objects inside it can still mutate:
t = ([1, 2],)
t[0].append(3)
print(t)Verified output: ([1, 2, 3],)
No error raised. t[0] = anything fails with TypeError, but t[0].append succeeds because the list itself is mutable. Hashability rules follow the same logic, which is why a tuple containing a list cannot be a dict key.
Defensive patterns that prevent leaks
- Copy inputs you must not own: work = list(source) at the top of a function.
- Return copies when exposing internals: return dict(self._data) instead of the live dict.
- Prefer immutables for shared config: tuples and frozensets cannot be silently mutated.
- Document ownership: if a function mutates its argument on purpose, say so in the docstring, because the signature gives no hint.
- Watch defaults and class attributes: both create one object shared by every call or instance, covered in depth in the mutable-defaults article in this library.
Quick drill
Predict before running:
x = [0]
y = x
z = list(x)
x.append(1)
print(y, z, x is y, x is z)Answer: [0, 1] [0] True False. y rides along, z is a separate snapshot. If any part felt uncertain, do the trace-table-with-object-IDs method on paper once and it will stick.
The multiplication list trap: [[0] * n] * n
One of the most frequently asked dry-run code questions tests list multiplication when building 2D grids or matrices. learners frequently write grid = [[0] * 3] * 3 to build a 3x3 tic-tac-toe board. Let us trace what happens when assigning one cell:
grid = [[0] * 3] * 3
grid[0][0] = 99
print(grid)Verified output on Python 3.12.10: [[99, 0, 0], [99, 0, 0], [99, 0, 0]]
Assigning cell [0][0] mysteriously modified the first column across all three rows. Why? The inner [0] * 3 creates a single list object: obj#1 containing [0, 0, 0]. The outer multiplication * 3 does not copy obj#1; it creates an outer list containing three references pointing to the exact same obj#1. Modifying grid[0][0] mutates obj#1, which all three rows display.
The correct idiomatic fix is using a list comprehension to ensure each row allocates an independent list object: grid = [[0] * 3 for _ in range(3)]. Re-running with the comprehension produces the intended output: [[99, 0, 0], [0, 0, 0], [0, 0, 0]].
Identity versus equality: is versus ==
practice problems regularly test whether learners understand the distinction between identity (memory address) and equality (value contents):
x = [1, 2, 3]
y = [1, 2, 3]
print('Equality:', x == y)
print('Identity:', x is y)Verified output: Equality: True Identity: False
Here x == y evaluates to True because Python traverses the elements and checks equality. However, x is y evaluates to False because x and y occupy different memory blocks (id(x) != id(y)). Now compare small integers and string interning, where CPython caches objects between -5 and 256 for performance, causing a = 100; b = 100; a is b to return True. Never use is for value comparisons; reserve is exclusively for identity checks against singletons like None.
Production API defense: immutable data structures
In multi-threaded web servers or shared memory caches, aliasing bugs cause unpredictable race conditions where request A mutates data being read by request B. To eliminate aliasing hazards permanently, use immutable structures: tuples instead of lists, frozenset instead of set, and frozen dataclasses or NamedTuples for domain transfer objects: @dataclass(frozen=True) class UserPayload. When mutation is syntactically impossible, shared state bugs cannot occur.
Four Critical Traps in Python Object Aliasing
- The 2D matrix multiplication trap: Writing
grid = [[0] * 3] * 3allocates one single 3-element list in memory and repeats its pointer three times. Updatinggrid[0][0] = 7mutates all three rows simultaneously. - Shallow copy leaks on nested objects:
copy.copy(data)duplicates the top-level container, but nested child dictionaries or lists continue sharing memory addresses. Onlycopy.deepcopy()recursively duplicates child structures. - Mutating objects within immutable containers: A tuple
t = (1, [2, 3])cannot have elements reassigned (t[0] = 5raises TypeError), but its mutable child list CAN be mutated in place (t[1].append(4)), changing the observable contents of the tuple. - Confusing
iswith==:==checks value equality (a.__eq__(b)), whileisverifies exact memory address identity (id(a) == id(b)). CPython caches small integers (-5 to 256) and interned strings, leading to misleadingisbehavior that fails on larger integers.
Aliasing Practice Drills & Step-by-Step Solutions
Drill 1:
Trace the exact memory state of this list assignment:
a = [10, 20]
b = a
b += [30]
print('a:', a, 'b:', b, 'Same id:', a is b)Solution: In Python, list.__iadd__ performs in-place mutation (equivalent to a.extend([30])). Both a and b reference the same list object at memory address id(a). Output: a: [10, 20, 30] b: [10, 20, 30] Same id: True.
Drill 2:
Contrast Drill 1 with concatenation b = b + [30]:
a = [10, 20]
b = a
b = b + [30]
print('a:', a, 'b:', b, 'Same id:', a is b)Solution: The + operator allocates a brand new list in memory and rebinds b to the new address. Variable a remains bound to the original list [10, 20]. Output: a: [10, 20] b: [10, 20, 30] Same id: False.
Drill 3:
What is the correct way to initialize a 3x3 grid of independent zeros?
Solution: Use a list comprehension: grid = [[0 for _ in range(3)] for _ in range(3)]. This evaluates the inner list allocation three distinct times, ensuring each row occupies a unique memory address.
Test your pointer reasoning hands-on in our Lists Foundations Practice workspace and read our related article on Mutable Default Arguments.
Related Video
A curated companion video with short authored timestamps and a concise summary.
Short timestamps & notes
[00:00] Problem statement
[01:10] Demonstration of shared state
[02:40] Fix patterns and best practices
Summary: Concise explanation and code examples showing why mutable defaults persist between calls and how to avoid the trap.