datarekha
Python Medium Asked at AmazonAsked at GoogleAsked at MicrosoftAsked at Palantir

How does Python's mutable vs immutable distinction affect function arguments and default values?

The short answer

Python passes references to objects, so a mutable argument (list, dict, set) can be modified inside a function and the change is visible to the caller. An immutable argument (int, str, tuple) cannot be mutated in place, so rebinding the local name only affects the local scope. The most common trap is using a mutable object as a default argument value, which is shared across all calls.

How to think about it

The interviewer wants to see that you understand Python’s object model, not just surface syntax. The key insight: Python always passes a reference to the object. What matters is whether that object can be changed in place or not.

For immutables (int, str, tuple, frozenset), “mutating” means creating a new object. The function’s local name points to the new object while the caller’s name still points to the original — they naturally diverge.

For mutables (list, dict, set, most class instances), calling a method like .append() or .update() changes the object itself. Both the caller’s name and the function’s local name still point to the same object, so the caller sees the change.

Run it and compare

The key rule

The distinction is not “pass by value” or “pass by reference” — Python is often called pass by object reference or pass by assignment. Think of it as: “the function receives a copy of the pointer”. If you mutate through that pointer, the caller sees it. If you reassign the pointer (lst = something_else), only your local copy moves; the caller’s pointer is unchanged.

Intentional mutable default: accumulator pattern

Occasionally the shared-default behaviour is deliberately exploited as a simple cache:

def fib(n, _cache={0: 0, 1: 1}):
    if n not in _cache:
        _cache[n] = fib(n - 1) + fib(n - 2)
    return _cache[n]

This is obscure; prefer @functools.lru_cache for caching and None sentinel for everything else.

Learn it properly Errors & Exceptions

Keep practising

All Python questions

Explore further

Skip to content