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 originalisTrueinside the function, and aswap(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.