⭐ Pass by Value vs. Pass by Reference in Python
Many languages support either Pass by Value (copy of data is passed) or Pass by Reference (address/reference is passed).
But Python works differently.
✅ Important: Python Uses “Pass-by-Object-Reference”
This means:
- When you pass a variable to a function, the reference to the object is passed.
- But behavior depends on the type of object:
- Immutable objects behave like Pass by Value
- Mutable objects behave like Pass by Reference
🔹 1. Immutable Objects (Pass by Value-like behavior)
Immutable objects include:
intfloatstrbooltuple
When an immutable object is passed to a function:
✔ A reference is passed
❌ But you cannot change the original object inside function
✔ So it behaves like Pass by Value
Example:
def modify(x):
x = x + 10
print("Inside function:", x)
a = 5
modify(a)
print("Outside function:", a)
Output:
Inside function: 15
Outside function: 5
🔥 The original value a is NOT changed because integers are immutable.
🔹 2. Mutable Objects (Pass by Reference-like behavior)
Mutable objects include:
listdictset
When a mutable object is passed:
✔ Reference is passed
✔ You CAN modify the original object
✔ Behaves like Pass by Reference
Example:
def modify(lst):
lst.append(100)
print("Inside function:", lst)
a = [1, 2, 3]
modify(a)
print("Outside function:", a)
Output:
Inside function: [1, 2, 3, 100]
Outside function: [1, 2, 3, 100]
🔥 The original list a is CHANGED because lists are mutable.
⭐ Conclusion (Exam Answer)
| Type | Behavior | Explanation |
|---|---|---|
| Immutable objects | Pass by Value-like | New object created inside function |
| Mutable objects | Pass by Reference-like | Changes affect original object |
| Python Model | Pass-by-Object-Reference | Function gets reference to object |
📌 3. Diagram Explanation (Very Important for Exams)
For Immutable:
a → 5
modify(a)
Inside function: x → 15 (new object)
Outside: a → 5 (unchanged)
For Mutable:
a → [1,2,3]
modify(a)
Inside: list is modified
Outside: a → [1,2,3,100]
🔹 4. Rebinding vs Mutating
Rebinding (Does NOT affect original)
def func(x):
x = [10, 20] # rebinding
a = [1, 2, 3]
func(a)
print(a) # unchanged
Mutating (Affects original)
def func(x):
x.append(99) # mutation
a = [1, 2, 3]
func(a)
print(a) # changed
💡 Key Exam Points (Write these in your answer):
✔ Python uses pass-by-object-reference
✔ Immutable → behaves like pass-by-value
✔ Mutable → behaves like pass-by-reference
✔ Depends on object type, not function
✔ Rebinding vs Mutating is the key difference
