Mutable vs Immutable Objects Passed to Python Functions

⚡ Direct Answer & Key Takeaway

In Python, arguments are passed by object reference, meaning the parameter receives a reference to the caller's object rather than a separate copy. When an immutable object like an int, str, or tuple is passed, rebinding the parameter creates a new local object and leaves the caller unchanged. When a mutable object like a list or dict is passed, in-place mutations such as append() or item assignment alter the original object directly.

1. How Object References Work Across Function Calls

CBSE Class 12 Computer Science questions frequently test whether a function modifies the variable passed by the caller. Instead of traditional pass-by-value or pass-by-reference labels from C++, Python uses pass-by-object-reference. Before a function runs, the argument variable in the caller points to an object in memory identified by a unique memory address, viewable via id(). When the function starts, the formal parameter becomes a second label bound to that exact same object. At entry, id(param) equals id(arg). What happens next depends on mutability and the operation performed inside the function body. Immutable objects—including int, float, bool, str, and tuple—cannot be altered in place. Any operator such as += on an integer or + on a string constructs a brand-new object and binds the local parameter to that new address, leaving the caller's binding intact.

  • At function entry, both the caller argument and formal parameter reference the same id().
  • Immutable types (int, float, bool, str, tuple) never change content at an existing memory address.
  • Reassigning a parameter inside a function only shifts the local label to a new object.

2. In-Place Mutation vs Rebinding for Mutable Types

Mutable built-in types such as list, dict, and set allow content modifications without changing the object's memory identity. When a function calls methods like list.append(), list.sort(), dict.update(), or assigns to an index such as items[0] = 99, it edits the shared heap object directly. Because the caller's variable still points to that same object, every change remains visible after the function returns—even without a return statement. However, board exam traps often replace an in-place operation with an assignment statement like items = [10, 20] or items = items + [4]. Using the = operator or + concatenation creates a fresh list and rebinds only the local parameter name. Consequently, the caller's list stays untouched. Notice the crucial distinction with += on a list: items += [4] invokes __iadd__, mutating the original list in place, whereas items = items + [4] creates a new list.

  • In-place methods (.append, .pop, .sort, .update) and index/key assignments mutate caller state.
  • Direct rebinding (param = [...]) breaks the link to the caller's list without altering it.
  • On lists, += mutates in place while = param + [...] creates a separate list object.

3. Protecting Caller Data and Tracing Exam Snippets

To avoid unintended side effects when passing a list or dictionary into a helper function, pass a shallow copy using data.copy() or slicing data[:]. If a list contains nested sublists, use copy.deepcopy(data) from the copy module so inner lists are not shared between caller and callee. For CBSE 083 output-prediction questions, follow a disciplined three-step trace: track each variable's type, check whether each line inside the function mutates an index/method or rebinds with =, and update caller state only for in-place mutations on shared objects. Pay close attention to tuples holding mutable elements, such as ([1, 2], 'A'): the outer tuple cannot be reassigned, yet t[0].append(3) succeeds because the nested list inside the tuple remains mutable. Mastering this distinction eliminates guessing on 2-mark and 3-mark output questions.

  • Use data.copy() or data[:] for flat lists and copy.deepcopy() for nested lists.
  • Trace every line as either a mutation (updates shared object) or rebinding (local only).
  • Always inspect element mutability when a tuple wraps a list or dictionary.

4. Tracing Immutable Rebinding vs In-Place List & Dict Mutations

def update_records(score, marks_list, tag_dict, copied_list):
    score = score + 10              # Rebinds local int (immutable)
    marks_list[0] = 95              # In-place index mutation
    marks_list.append(88)           # In-place method mutation
    marks_list = marks_list + [100] # Rebinds local name only!
    tag_dict["status"] = "Pass"     # In-place dict mutation
    copied_list.append(999)         # Mutates shallow copy only

student_score = 75
exam_marks = [70, 82]
student_info = {"subject": "CS"}

update_records(student_score, exam_marks, student_info, exam_marks.copy())

print("Score:", student_score)
print("Marks:", exam_marks)
print("Info:", student_info)

Verified Console / Dry-Run Output:

Score: 75
Marks: [95, 82, 88]
Info: {'subject': 'CS', 'status': 'Pass'}

5. Effect of Operations on Mutable vs Immutable Function Arguments

Argument TypeMutabilityOperation Inside FunctionEffect on Caller Variable
int / float / strImmutablex = x + 1 or s += '!'Unchanged; local parameter rebinds to a new object
tupleImmutable containert = t + (4,)Unchanged; + creates a new tuple locally
listMutablelst.append(5) or lst[0] = 9Modified in place; change persists in caller
listMutablelst = lst + [5] or lst = [1]Unchanged; local parameter rebinds to a new list
dictMutabled['k'] = 10 or d.pop('a')Modified in place; change persists in caller
🎯 1-on-1 Live Mentorship & Free Study Kit

Master CBSE 083 Function Tracing in a Free 1:1 Practice Pod

Practice live output-tracing drills on object references and mutability with 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 diagnostic session to sharpen your CBSE 083 accuracy.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Assuming x += 1 inside a function changes the caller's integer variable outside the function.
  • Avoid Mistake: Confusing marks = marks + [100] (which creates a new local list) with marks.append(100) (which mutates in place).
  • Avoid Mistake: Forgetting that passing a list without .copy() shares the exact same object with the caller.
  • Avoid Mistake: Believing a tuple containing a list cannot have its inner list modified via t[0].append(x).
  • Examiner / Mentor Tip: State the exact phrase 'passed by object reference' rather than 'pass by value' during viva questioning.
  • Examiner / Mentor Tip: Check every = assignment on a list parameter—many CBSE output questions hide a rebinding line right after an append().
  • Examiner / Mentor Tip: Verify whether the caller prints the original variable or a returned value before writing your final output.

7. Interactive Concept Check Quiz

Question: What is the output of:\ndef tweak(num, data):\n num += 5\n data.append(num)\n data = [99]\na, b = 10, [1, 2]\ntweak(a, b)\nprint(a, b)

8. Frequently Asked Questions

Does passing an integer with += inside a Python function update the original variable?
No. Integers are immutable, so n = n + 1 or n += 1 creates a new integer object bound only to the local parameter. The caller's variable still points to the original number unless the function returns the new value and the caller reassigns it.
Why do items += [4] and items = items + [4] behave differently inside a function?
items += [4] calls the list's in-place __iadd__ method, modifying the original list seen by the caller. In contrast, items = items + [4] builds a brand-new concatenated list and rebinds only the local parameter, leaving the caller's list untouched.
Can a mutable list stored inside an immutable tuple be changed inside a function?
A tuple itself cannot be reassigned or resized, so t[0] = 99 raises a TypeError. However, if t[0] is a mutable object such as a list, calling t[0].append(99) mutates that inner list in place while keeping the tuple's element references intact.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class