Python Call by Value or Reference?

If you are a newbie to the world of Python then many you might have come across a situation where a variable assignment changed upon using it as an argument of a function when you were not expecting it to change. Then some other time when you are now expecting the variable value to change it didn’t. This all depends on if you are calling the variable by value or reference and if you have come across the above situation then you would have understood its neither of them.
Let’s begin with the basic understanding of the above-mentioned words.

Call by value

When we call a function we send variable name having a value assigned to it. Now if we change the value or modify it that modified variable won’t be available to us outside the function to use. Still, the value assigned to that variable remains the same if we want to use them outside of the function. 

Call by reference

When we call a function we send variable name having the address of a value assigned to it. Now if we change the value or modify it that modified variable will be available to us outside the function to use. The value assigned to that variable no longer remains the same if we want to use them outside of the function.

The Combination

Python if combination of both worlds. It has two types of variables mutable and immutable. Immutable means the one which cannot be changed directly. Mutable are those which can be changed directly. If a mutable variable is used as an argument to a function then changing the variable assignment inside the function changes its value forever.  It is not true for immutable.

Let us observe the same with few examples

def strig(name):
    name="speedycode"
    print("inside the function", name)

name="codespeedy"
print("before function call", name)
strig(name)
print("after function call", name)

Output:
before function call codespeedy
inside the function speedycode
after function call codespeedy

As we can observe that string being an immutable datatype changing the string assigned to the variable “name” doesn’t change its value outside the function.

def strig(name):
    name.append("speedycode")
    print("inside the function", name)

name=["codespeedy"]
print("before function call", name)
strig(name)
print("after function call", name)
Output:
before function call ['codespeedy']
inside the function ['codespeedy', 'speedycode']
after function call ['codespeedy', 'speedycode']

The list is a mutable data structure, changes in it are reflecting outside the function as well.
Examples of mutable objects/datatype/data structures is:  list, dict, set, byte array
Examples of mutable objects/datatype/data structures is:  int, float, complex, string, tuple.

That’s it for the article guys. I tried my best to simplify what I understand by the call by value or call by reference. Please do comment if you can simplify it.

Leave a Reply

Your email address will not be published. Required fields are marked *