What is pass by reference in python?

Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment is the cause behind the confusion at the fundamental level. 

In the article, we will be discussing the concept of how to pass a value by reference in Python and try to understand pass-by-reference examples in Python.

Pass by value and pass by reference in Python

You might want to punch something after reading ahead, so brace yourself. Python’s argument passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”. 

The paradigms of “Pass by value”, “Pass by Reference” and “Pass by object Reference” can be understood by exploring the below example functions. Look into the two functions defined below:

Python3

def set_list[list]:

    list = ["A", "B", "C"]

    return list

def add[list]:

    list.append["D"]

    return list

my_list = ["E"]

print[set_list[my_list]]

print[add[my_list]]

Output:

['A', 'B', 'C']
['E', 'D']

Now, let’s explore the above code, 

The variable is not the object

Here “a” is a variable that points to a list containing the element “X” and “Y”. But “a” itself is not the list. Consider “a” to be a bucket that contains the object “X” and “Y”. 

 a = ["X", "Y"]

What is Pass by Reference In Python?

Pass by reference means that you have to pass the function[reference] to a variable which refers that the variable already exists in memory. 

Here, the variable[ the bucket] is passed into the function directly. The variable acts as a Package that comes with its contents[the objects].

In the above code image both “list” and “my_list” are the same container variable and therefore refer to the exact same object in the memory. Any operation performed by the function on the variable or the object will be directly reflected by the function caller. For instance, the function could completely change the variable’s content, and point it at a completely different object: 

Also, the function can reassign the contents of the variable with the same effect as below: 

To summarize, in pass-by-reference the function and the caller use the same variable and object.

What is Pass by Value In Python?

In this approach, we pass a copy of actual variables in function as a parameter. Hence any modification on parameters inside the function will not reflect in the actual variable.

The same is true for any operation performed by the function on the variable or the object 

To summarize the copies of the variables and the objects in the context of the caller of the function are completely isolated.

In this tutorial, we will learn how to use pass by reference in Python. Variables work differently in Python than in any other programming language known to us. It is a memory location with a unique address whereas in Python, variables are not declared beforehand but the data decides the data type.

Table of Contents

  1. What is pass by reference
  2. Pass by reference vs value in Python
  3. Python Object Model
  4. Closing Thoughts

What is pass by reference?

Before we jump into the technical details, let's first see what does pass and by reference actually mean.
By pass we mean to provide an argument to a function. Whereas by reference means that the argument that has been passed to the function is a reference to a variable that is already existing in the memory. Now that we have cleared that, now we can learn about pass by reference.

In pass by reference, the variable is passed into the function directly while the variable acts as a Package that comes with the objects. Because you've given the function a reference to an existing variable, any operations you execute on it will have a direct effect on the variable it refers to.

Pass by reference vs value in Python

When you give function parameters via reference, you're just passing references to values that already exist. When you pass arguments by value, on the other hand, the arguments become independent copies of the original values.

Pass by value

Any other operation performed will not have any effect on the original value as the argument passed to the function is copied. It only changes the value of the copy created within the function.

Input:

def function[int]:
  int+=100
  print["Inside function call ",int]

int=100
print["Before function call ",int]
function[int]
print["After function call ",int]

Here, a copy of the argument is created, and changes are made to that copy such that the original value is not affected. As a result, the original value is printed after the function call.

Output:

Before function call 100                                       
Inside function call 200
After function call 100 

In this, we assigned the variable the value '100' and changed it to '200', but the change was not seen outside the function i.e. int is still '100'. Hence proved, it is pass by value method.

Pass by reference

This method passes a reference to the original arguments, and any operation performed on the parameter affects the actual value. It alters the value in both function and globally.

Input:

def function[int]:
    int.append['B']print["Inside function call",int]
    
int=['A']
print["Before function call",int]
function[int]
print["After function call",int]

When a list is used, its reference is supplied into the function, and any modifications to the list have an effect even after the method has been called.

Output:

Before function call ['A']          
Inside function call ['A', 'B']                  
After function call ['A', 'B']

In the above example, function[] returns a string and also modifies the value of int. This shows that Python supports the pass by reference method.

Python Object Model

It's best if we first understand what Python objects are and how to characterize them. In Python, everything is an object. Object's identity, data type and object's content characterize every object.

# the identity of `int`
id[int]
3578332784044       

# the type of `int`
type[int]
   
   
# the contents of `int`
int [1, 2, 3]           

As we can see above, id is the built-in function you use to query the identity of an object, and type is the built-in function you use to query the type of an object.

Closing Thoughts

Python operates differently than the other programming languages when it comes to the moving of the arguments. Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. One can learn about other Python-related concepts here.

What is pass by reference and pass by value in Python?

Pass by reference means that you have to pass the function[reference] to a variable which refers that the variable already exists in memory. Here, the variable[ the bucket] is passed into the function directly. The variable acts as a Package that comes with its contents[the objects].

What is meant by pass by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

Is Python function pass by reference?

Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value.

How do you pass a string by reference in Python?

The pythonic way of dealing with this is to hold strings in an list and join them together once you have all the pieces. Python never passes by reference. It passes references, but "pass by reference" is already taken for another argument passing style [one which permits, for example, the function swap[a, b] ].

Chủ Đề