Aliasing and Shared State: Avoiding Mutable Object Surprises
Concrete strategies to detect when variables share objects, how to represent aliases in trace tables, and production fixes for accidental shared state.
Ameer Abdullah
Data Science Graduate · AI/ML & Data Science
Aliasing occurs when two or more names reference the same mutable object. In a trace, this often looks like identical values in multiple columns - but the key signal is identity, not equality.
Representation trick: assign object ids (obj#1, obj#2) in a separate column. When you mutate obj#1, update the shared object's contents rather than each name's copy. This prevents a common interview error where candidates accidentally treat aliases as independent values.
Example code: a = [1,2,3] b = a b.append(4) print(a) # [1,2,3,4]
Trace explanation: both `a` and `b` point to obj#1. When `b.append(4)` mutates obj#1, the change is visible through `a` immediately. In interview narration, explicitly say 'a and b reference the same list object (obj#1) so the append mutates the shared object.'
Production fix patterns: avoid storing mutable defaults in function signatures, prefer copying inputs with `list(x)` or `dict(x)` when you need isolated state, or use immutable types where possible. If high throughput requires mutation for performance, document and constrain ownership semantics clearly in code comments and API docs.
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.
Practice what you just learned
Apply these concepts in PyCodeIt's interactive sandbox with real problems.
Start Python Practice