![]() |
VOOZH | about |
In languages like C++ or Java, concepts like pass-by-value and pass-by-reference are commonly used. Python works differently and follows a pass-by-object-reference approach:
Python passes object references to functions, so mutable objects can be modified inside the function without creating a copy. This means both the caller and the function share the same object. With mutable types like lists, dicts and sets, any changes made inside the function will reflect outside as well.
['X']
Explanation: lst and my_list both point to the same list. Since .append() modifies the list in place, the change is visible outside the function.👁 Image
['X']
Explanation: Function rebinds list to a new list object. This does not affect my_list. list now refers to a new object inside the function and my_list still refers to the original object, which remains unchanged.
['X', 'B']
Explanation: Function modifies the list in-place. The change is visible outside. Since list.append("B") changes the contents of the list in place, my_list is also modified.
Inside function: [1, 2, 3, 4] Outside function: [1, 2, 3, 4]
Explanation: List is mutated inside the function and the changes persist outside because both lst and a refer to the same object.
In pass-by-value, a copy of the variable is passed, so changes inside the function don't affect the original. While Python doesn't strictly follow this model, immutable objects like int, str, and tuple behave similarly, as changes create new objects rather than modifying the original.
['X']
Explanation: Although both my_list and list point to the same object, no changes were made. So the object remains exactly the same.
['X']
Explanation: Inside the function, list is reassigned to a new object. But this does not change my_list outside the function.
Inside function: 15 Outside function: 5
Explanation: Integers are immutable, so modifying x inside the function creates a new object. The original num remains unchanged.
Aspect | Pass by Reference | Pass by Value |
|---|---|---|
Object Type | Mutable (list, dict, etc.) | Immutable (int, str, etc.) |
What is Passed | Reference to object | Reference to object |
Can Modify in Function? | Yes (affects original) | No (new object created) |
Affects Original? | Yes | No |
Typical Behavior | Like aliasing | Like copying |