Skip to the solution
EasyBackend9 min read

Is Python pass-by-value or pass-by-reference?

586 views

The problem

Question presented to candidate: "If I pass a list into a function and the function changes it, the caller sees the change. If I pass an integer and the function changes it, the caller does not. So is Python pass-by-value or pass-by-reference?"

What a strong answer should cover:

  • Neither in the classic sense: the function receives a reference to the same object, and that reference is copied into a new local name β€” called call by sharing, pass by object reference, or, in the Python FAQ, pass by assignment
  • Mutating the object through the parameter (items.append(x)) is visible to the caller; rebinding the parameter (items = ...) only changes the local name
  • Why immutable arguments (int, str, tuple) look like pass-by-value: nothing can change them, so every "change" is a rebinding
  • Proof points: param is original is True inside the function, and a swap(a, b) function cannot work, which it could with true pass-by-reference
  • The += subtlety (in place for a list, a new object for an int or tuple) and the defensive-copy fix, including why a shallow copy may not be enough

Code / implementation expected: Optional β€” a short function that mutates vs one that rebinds, showing the caller's object afterwards.

  • functions
  • objects

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

9 min read Β· 10 sections

Run the code

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

PythonMutate vs rebind: what the caller sees
PythonDefensive copies, tuples holding lists, and returning instead of out-parameters

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 17 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 nextEasy

How do pyproject.toml, tomllib, and uv/pyproject workflows fit together?

Continue