Skip to the solution
MediumDSA10 min read

How does Python's name and object reference model work?

487 views

The problem

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; is and id() compare identity.
  • Rebinding a name (a = a + [3]) vs mutating the object (a.append(3)); += mutates lists in place but rebinds for immutable types like int and tuple.
  • Function calls bind parameters to the caller's objects ("call by sharing"), so mutation is visible to the caller and rebinding is not.
  • del removes a name, not an object; CPython frees the object when its reference count reaches zero, and sys.getrefcount shows the count (with caveats such as immortal objects in 3.12+).
  • Classic traps: [[0] * 3] * 2 shares rows, and t[0] += [x] on a tuple both mutates the list and raises TypeError.

Code / implementation expected: Optional β€” predict output of an aliasing snippet, using is or id() to explain it.

  • memory
  • references

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonNames, objects and aliasing: rebinding vs mutation
PythonThe classic traps, reference counts and when objects die

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 86 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does the bisect module work?

Continue