Python - Pass by value or by reference
Python uses a mechanism, which is known as Call by Object Reference or Call by assignment. When an immutable arguments like integers, strings or tuples are passed to a function, the passing is like call-by-value because the immutable objects can not changed by passing to a function as arguments. Whereas When a mutable arguments like lists or dictionaries are passed to a function, the passing is like call-by-reference. Any changes performed on mutable arguments inside the function is also reflected outside the function.
Example: Call-by-value
In the example below, string x is passed to the function test. As string is a immutable object, the passing acts like call-by-value. Inside the function string x is changed which is not reflected outside the function.
def test(str): str = str + " World" return str x = "Hello" print(test(x)) print(x)
The above code will give the following output:
Hello World Hello
Example: Call-by-reference
In the example below, list MyList is passed to the function test. As list is a mutable object, the passing acts like call-by-reference. Inside the function list MyList is changed which is also reflected outside the function.
def test(x): x.append(50) return x x = [10, 20] print(test(x)) print(x)
The above code will give the following output:
[10, 20, 50] [10, 20, 50]
❮ Python - Functions