Question presented to candidate:
"People say Python has no variables, only names. What does that mean? Explain what happens in memory when you write a = [1, 2] and then b = a."
What a strong answer should cover:
- Every value is an object with an identity, a type and a value; a name is a label in a namespace that refers to an object. Assignment binds a name and never copies.
- Aliasing: two names can refer to one object, so a mutation through one is visible through the other;
isandid()compare identity. - Rebinding a name (
a = a + [3]) vs mutating the object (a.append(3));+=mutates lists in place but rebinds for immutable types likeintandtuple. - Function calls bind parameters to the caller's objects ("call by sharing"), so mutation is visible to the caller and rebinding is not.
delremoves a name, not an object; CPython frees the object when its reference count reaches zero, andsys.getrefcountshows the count (with caveats such as immortal objects in 3.12+).- Classic traps:
[[0] * 3] * 2shares rows, andt[0] += [x]on a tuple both mutates the list and raisesTypeError.
Code / implementation expected: Optional β predict output of an aliasing snippet, using is or id() to explain it.