Identity asks whether two references reach the same object. Aliasing means multiple names or slots refer to that one object.
Follow references through repeated rows, argument passing and copies to explain which changes become visible elsewhere.
A cleaner edits a batch, but the audit's “before” data changes too. To diagnose that failure, track which objects the names reach, not just what they print. Assignment to a name creates a binding; it does not copy the object. This lesson builds on functions and nested lists to separate mutation, rebinding, and copying.
![Two labels "raw" and "cleaned" both pointing at one list before an append; after cleaned = [...] rebinds cleaned onto a new stripped list while raw still points at the original, unchanged](/api/assets/python/assets/010bd0bfbabd2b83.png)
An audit that always says "nothing changed"
A cleaning stage trims whitespace from every field of a batch. An audit stage runs later and compares the cleaned rows against the raw ones — and always reports that nothing changed:
Nobody edited raw on purpose. cleaned = raw never copied anything — it just
gave the same list a second label, so a change through one name shows up through
the other. The fix is for the cleaner to build a new list instead of mutating
the one it was handed:
raw = ["alpha ", " beta"]
cleaned = raw
cleaned = [f.strip() for f in cleaned] # a comprehension builds a NEW list
print(raw)Step through the same audit code and watch the same column. It's True only
while both names point at one object:
Drawn out, the end state looks like this:
Until the append, both names pointed at list #1, so it changed the one list they
shared. The comprehension built list #2, and = moved one arrow onto it. That is
the whole fix for the audit bug: the cleaner should build new rows instead of
editing the rows it was handed.
Preparing this topic’s interactive investigation…
Follow the arrow that an operation changes
Bring two earlier ideas together: assignment binds a name; indexing selects an object inside a collection. Those operations reach different places in a nested batch. Copying the outer list changes only the first layer of arrows.
The first line prints False True: two outer lists, one shared inner row.
append changes the snapshot's outer list; the indexed assignment changes the
shared row. The original therefore becomes [['pending']], while the snapshot
also contains ['new']. An unchanged outer length does not prove isolation.
For an audit snapshot of lists of strings, [row.copy() for row in raw] copies
the objects that will actually be edited. For rows containing nested dictionaries,
that may still be too shallow. Draw the mutated object first, then choose the
copy depth. deepcopy is not a universal isolation boundary: classes can customise
copying, and resources such as files cannot simply be duplicated this way.
Before the snapshot exercise, change the indexed assignment above to
snapshot[0] = ["clean"]. Predict which list now retains the spaces, then run it.
Explain which arrow moved; saying only “it made a copy” leaves out the cause.
Passing an argument is binding a name
A function call binds each parameter to the object supplied by its argument. The parameter is a local name; rebinding it does not assign to the caller's name. Mutating the shared object can still affect the caller:
def clean(row):
row.append("checked") # mutates the object the caller passed
row = ["fresh"] # rebinds row — a LOCAL name only
row.append("new")
row = ["a"]
clean(row)
print(row)A function that needs to hand back a changed version should return it. A function that mutates its argument should say so in its name.
The grid that repeats one row three times
* on a list repeats references, not copies. For numbers that's harmless,
because a number can't be mutated — for rows of a grid it's a trap:
Only the top-left cell should become 1. Run it, see every row change, then fix the first line so each row is its own list.
The inner [0] * 3 is safe, because it repeats references to one 0, and 0
can't change. The outer * 3 repeats references to one list, and a list can. A
comprehension evaluates [0] * 3 fresh on every loop, so each row really is a
separate object.
Shallow copy vs. deep copy
When a stage genuinely needs its own version of the data, it copies — but "copy"
has two depths. A shallow copy (list(x), x.copy(), x[:]) makes one new
outer container, filled with references to the same inner items. A deep
copy (copy.deepcopy(x)) recursively copies supported nested objects, preserving sharing through a memo.
Custom classes can control copying; not every resource can be copied:
That's not a naive recursive copy — a naive one would copy tags twice (breaking
the sharing) and recurse forever on the cycle. deepcopy keeps a memo, a
dict from id(original) to the copy already made for it, and checks it before
copying anything. Shallow-copy when you're only changing the top level; deep-copy
when you're about to change something nested; skip copying entirely when a stage
can just return new rows instead of editing the ones it was handed.
Quick practice
The next prediction observes this CPython runtime's reuse of objects. Its identity output is not a portable guarantee for all Python implementations; use equality for the application decision.
a = 256
b = 256
x = "".join(["qu", "arry"])
y = "quarry"
print(a is b, x is y)A plain default=None couldn't tell "no default given" apart from "the default
really is None". A freshly built object() can, because no caller could ever
pass in that exact object by accident — that's what is is actually for.
🎯 Your turn
The inspector's first piece replays how a stage script binds its names, and
reports which ones end up sharing an object. Each step is [target, op, source]:
[name, "new", null]bindsnameto a brand-new empty list[name, "alias", other]bindsnameto the same objectotherpoints at[name, "copy", other]bindsnameto a shallow copy of that object
Write shared_names(steps): run the steps in a dict that plays the part of a
namespace, then return every group of two or more names that end up pointing at
one object — names sorted within each group, groups sorted.
[["raw", "new", null], ["clean", "alias", "raw"], ["backup", "copy", "raw"]]→[["clean", "raw"]][["a", "new", null], ["b", "alias", "a"], ["a", "new", null]]→[], because rebindingamoved onlya
Hint: a dict keyed by id(obj) collects the names sharing each object — ids
are safe here because every object stays alive in your namespace while you're
looking at it.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Quarry's tagger adds a tag to a row. The first version did row.append(tag), which edited the caller's row behind its back. Write tag_row(row, tag) returning [tagged, row]: tagged is a NEW list with tag on the end, and row is the caller's list, which must come back unchanged.
Write marked_grid(rows, cols, cells). Build a rows × cols grid of zeros, set every [r, c] in cells to 1, and return the grid. The starter builds the grid with *, so a mark in one row shows up in every row.
Quarry's audit keeps a snapshot of a batch before the cleaner strips every field in place. Write clean_with_snapshot(batch): take a snapshot, strip every field of every row IN PLACE (the cleaner must keep editing batch itself), and return {"before": snapshot, "after": batch}. The starter's snapshot gets cleaned too.
Write downstream_view(mode). Build the batch [["a", " b "], ["c"]]. Hand it to a stage in one of three ways, chosen by mode: "alias" passes the batch itself, "shallow" passes list(batch), and "deep" passes copy.deepcopy(batch). The stage appends a new row ["d"] to what it was given, and strips every field of its first row in place. Return [len(batch), batch[0]], which is what the ORIGINAL batch looks like afterwards.
Write your own clone(obj, memo=None) that deep-copies nested lists and dicts, returning every other value as it is. Like copy.deepcopy, it must keep a memo from id(original) to its copy, so that an object shared in two places is copied once, and a structure that contains itself is copied without infinite recursion. clone_check(kind) (given) builds a test structure and reports what your clone did with it. Do not use the copy module.
A teammate says: "Python passes lists by reference and ints by value. That's why a function can change my list but not my number." Explain what really happens when you call a function, and why their rule seems to work even though it's wrong.