A Python interview trace tests the operation and ownership rules that determine the result, not memorization of a printed string.
Python interview traces: explain aliasing, defaults and identity
Operation contract
The trace copies an outer list, checks the shared inner object, and mutates that object. It then uses a None-default function twice to prove that the two returned tag lists have distinct identity. A useful answer states when objects are allocated and which references still point to them before giving the output.
Failure and ownership boundary
Identity is not equality. Two different lists can compare equal, while one shared list can change beneath several names. Correcting a mutable default alone also does not copy a list supplied by a caller. Read Python function arguments: avoid shared mutable defaults, Python lists: slicing copies the outer sequence, not nested objects and Python closures: capture loop values at the intended time before translating these traces to concurrent work.
Working program
nested = [[125]]
outer_copy = nested.copy()
print(nested is outer_copy)
print(nested[0] is outer_copy[0])
outer_copy[0].append(75)
print(nested)
def new_tags(tags=None):
return [] if tags is None else tags
print(new_tags() is new_tags())Output
False
True
[[125, 75]]
FalseCosts and limits
An outer copy is O(n) reference work; identity tests compare object identity without traversing all elements. Equality of containers may traverse their contents.
Common Mistakes
- Explain ownership before naming the output.
- Do not use is as general value equality.
Connected lessons
Python lists: slicing copies the outer sequence, not nested objects, Python function arguments: avoid shared mutable defaults, Python closures: capture loop values at the intended time.
