Lesson · Functions
Python Argument Passing
45 min readPython Argument Passing
Python passes object references by assignment: a call creates new local names bound to the same objects supplied by the caller. Rebinding a parameter differs fundamentally from mutating the object it names.
Learning goals
- Explain what "pass by assignment" means: parameters join the caller's objects as extra names, with no copy at the call boundary.
- Predict whether a function will change the caller's data or leave it untouched.
- Tell rebinding a parameter apart from mutating the object it names, using the worked example's
mutateandrebind. - Explain why a mutable default such as
items=[]keeps state between calls. - Decide whether a function should mutate its argument or return a new object, and document that choice.
Mental model
A call copies nothing: each parameter is simply one more name bound to whatever object the caller passed. An argument therefore has only two possible fates inside a function, mutating the shared object, which the caller sees, or rebinding the local name, which the caller does not. Reading a function body gets easier once you ask that question per line: does this statement change the object, or only the name?
One object, two names
mutate the object, or move only the local name
Mental model
the same mechanism as a compact list
values ───┐
├──→ ["original"] one object, two names
items ────┘
↓ items.append("changed") mutation touches the object
["original", "changed"] visible through values as well
items = ["new"] rebinding moves only the local name
["new"] ←── items values still points at the old listCore idea
Python passes arguments by assignment: each parameter becomes a new local name bound to the very object the caller supplied, with no copy at the boundary. That one sentence predicts everything in this lesson: methods that mutate the shared object (append, sort) stay visible to the caller, rebinding the parameter does not, and a mutable default survives between calls because its expression was evaluated once.
Object-sharing model
A function call binds parameter names to the same objects supplied by the caller. Python does not copy an argument merely because it crossed a function boundary.
Mutable arguments
When a parameter refers to a mutable object, mutating that object is visible to every reference to it, including references held by the caller.
Immutable arguments
Rebinding a parameter to a new immutable value does not affect the caller's name. Operations on immutable objects typically produce new objects rather than modifying the original.
Rebinding vs mutation
This comparison separates Rebinding from mutation in the context of Python Argument Passing. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
Mutable default argument trap
Default argument expressions are evaluated once when the function is defined, not on every call. A mutable default can therefore retain changes between calls.
Walkthrough
values = ["original"]creates one list object, and the callmutate(values)binds the parameteritemsto that same object rather than to a copy.items.append("changed")mutates the shared list, so the firstprintshows["original", "changed"], a change the caller can see throughvalues.rebind(items)receives the same list, butitems = ["new"]builds a fresh list and points the local name at it; the returned list is new, andvaluesstill references the original.- Predict before running: which of the two calls changes the object
valuesrefers to, and which only changes what a parameter name points at.
Experiments to try
- Change
items.append("changed")inmutatetoitems = items + ["changed"]and rerun; the firstprintshows["original"]because+builds a new list instead of mutating the shared one. - Call
rebind(values)without using its return value, then printvalues; explain why this call leaves no trace in the caller whilemutate(values)does. - Write
def sorted_copy(items): return sorted(items)anddef sorted_in_place(items): items.sort(); run each onvaluesand record which one changes the caller's list. - Write
def collect(item, items=[]): items.append(item); return items, call it twice without a second argument, and watch the same list accumulate; then repair it withitems=Noneand a fresh list inside.
Common mistakes
- Expecting
items = ["new"]inside a function to change the caller's variable: assignment only rebinds the function's local name, so the caller's name still points at the original object. - Assuming a function that calls
items.append(...)oritems.sort()left the caller's data alone: those methods mutate the shared object, and every reference to it sees the change. - Building a default like
def collect(item, items=[]): the list is created once when the function is defined, so calls that omit the argument share one accumulating list. - Treating
=as a copy operation: assignment binds a second name to the same object, and only an explicit copy (for exampleitems[:]orlist(items)) gives the function a private version.
Practice: Easy
- Run the worked example unchanged and write down the three printed lines; next to each, state whether it shows the effect of a mutation or of a rebinding.
- Add a
print(items)insidemutatejust beforeappendand insiderebindright after the assignment, then compare those prints with what the caller sees. - Call
rebind(values)and bind its result tonew_values; printvalues,new_values, andvalues is new_valuesto confirm the two names point at different objects.
Practice: Medium
- Write
def clear_all(items): items.clear()anddef clear_copy(items): return []; call each on a fresh["a", "b"]list and state which caller list ends up empty. - Write
def collect(item, items=[]): items.append(item); return items, call it twice with no second argument, then rewrite it withitems=Noneand verify the accumulation stops. - Build both contracts for one operation:
def sorted_copy(items): return sorted(items)anddef sorted_in_place(items): items.sort(); return items; write one sentence documenting each side effect and pick which one you would expose in a public API.
Practice: Hard
- Design a
summarize(readings, out=None)function with a documented contract: fill the caller'soutlist when one is given, and return a fresh list otherwise; write one call per path and check without is Nonewhich caller objects were touched. - Build a tracer for the object graph: record
id(values)before the call, inside each function, and after; show with the numbers which call shared the object and which created a new one, then repeat with a string argument and explain the identical id pattern. - Audit three standard library operations you already use (for example
list.sort,sorted, anddict.update) and classify each as mutating the receiver, returning a new object, or both; turn the classification into a rule for deciding which style a new function should follow.
Lesson checklist
- I can predict whether a function will mutate the caller's object or only rebind its local name.
- I can explain why
valueschanges aftermutate(values)and not afterrebind(values). - I can choose between mutating an argument and returning a new object, and document the contract.
- I can explain why
def collect(item, items=[])accumulates state across calls.
Remember
Python passes arguments by assignment: parameters are extra names for the caller's objects, so mutation is shared and rebinding is not. The worked example shows the whole idea, `mutate` changes the list every reference can see while `rebind` only moves its own name, and the same fact explains the mutable default trap, where one list created at definition time serves every call.
Interview angles
What is the main purpose of **Object-sharing model**?+
A function call binds parameter names to the same objects supplied by the caller. Python does not copy an argument merely because it crossed a function boundary.
What should you pay attention to when using **Mutable arguments**?+
When a parameter refers to a mutable object, mutating that object is visible to every reference to it, including references held by the caller.
How does **Immutable arguments** fit into this lesson?+
Rebinding a parameter to a new immutable value does not affect the caller's name. Operations on immutable objects typically produce new objects rather than modifying the original.
Why does `items = ["new"]` inside a function not change the caller's `values`?+
Because assignment rebinds only the function's local name items to a fresh list; the caller's name values still points at the original object. Mutating that shared object, for example with items.append(...), is what the caller would see.