top of page
Writer's pictureNazeeruddin

Passing Arguments to Python Function call-by-value or call-by-ref?

Updated: Jan 28, 2023

The terminologies like call-by-value and call-by-reference are commonly using in C, C++ and other programming languages.


some people may say "mutable objects are call by ref, and immutable object are call by value". This is wrong.


Python is neither call by value nor call by reference. It is call by sharing (also known as "call by object" or "call by object sharing")


Why immutable objects are not call-by-value?

It acts like call-by-value:

But check out the following code:

The id of 'a' is identical to the id of 'b'. If the 'b' argument is call-by-value, this is impossible.


Everything in Python is an object, and the assignment operation is just binding a name to an object.

Here, the 'b' is another name to 'a' which is bound to the integer object '10'. The two names have identical ids since they are bound to the same object. If we change the integer, because of its immutability, a new integer object will be created, and the 'b' will be bound to the new object.


Why mutable objects are not call-by-reference?

We may think mutable objects are call-by-reference, if we see the below example:

But check out the following code:

Here, 'mylist' didn't change even if the 'xlist' was changed. If it's call-by-reference, this situation is hard to explain.


above example, after the 'xlist' = [99,88,77] was executed, the name xlist had been bound to another list object - [99,88,77].


since the mylist and xlist were bound to different list objects, the modification of xlist would not affect mylist anymore.


 

Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Commenting has been turned off.
bottom of page