Python Call By Reference or Call By Value
Below are some examples by which we can understand better about this:
Example 1: Call by Value in Python
In this example, the Python code demonstrates call by value behavior. Despite passing the string variable “Geeks” to the function, the local modification inside the function does not alter the original variable outside its scope, emphasizing the immutability of strings in Python.
Python3
# Python code to demonstrate # call by value string = "Geeks" def test(string): string = "w3wiki" print ( "Inside Function:" , string) # Driver's code test(string) print ( "Outside Function:" , string) |
Inside Function: w3wiki Outside Function: Geeks
Example 2: Call by Reference in Python
In this example, the Python code illustrates call by reference behavior. The function add_more()
modifies the original list mylist
by appending an element, showcasing how changes made inside the function persist outside its scope, emphasizing the mutable nature of lists in Python.
Python3
# Python code to demonstrate # call by reference def add_more( list ): list .append( 50 ) print ( "Inside Function" , list ) # Driver's code mylist = [ 10 , 20 , 30 , 40 ] add_more(mylist) print ( "Outside Function:" , mylist) |
Inside Function [10, 20, 30, 40, 50] Outside Function: [10, 20, 30, 40, 50]
Is Python call by reference or call by value
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. If you pass arguments like whole numbers, strings, or tuples to a function, the passing is like a call-by-value because you can not change the value of the immutable objects being passed to the function. Passing mutable objects can be considered as call by reference or Python pass by assignment because when their values are changed inside the function, then it will also be reflected outside the function.