Difference between pass by value and pass by reference in Python

Introduction

In Python, this question can be tricky specially if you come from a C++ background where pass by value and pass by reference is well defined. So what does that mean in Python? This question is repeatedly asked and answered online. My take on that is through the following example…

  • Define 4 data types as follows

  • Print the variables before we pass them to a function

  • Define a function that receives 4 variables and tries to modify them

  • Print the variables after modification inside the function

  • Call the function

  • Print the variables after we pass them to the function

  • If you run the code snippet above, you should get something like…

Discussion

Can you tell what happened? all variables got modified inside the function which is expected but only z retained the new value after exiting the function. Why ? I understand this can be confusing to beginners specially if you come from a C++ background. In Python there is no such thing as pass by value or pass by reference where pass by value means pass a copy of the variable so the original value is retained and pass by reference means pass a pointer to the memory location so modifying the object inside the function also modifies the original object.

In python, we bind a variable name to an object. This means we can use the variable name to modify the object inside the function (z.append in our case) but the moment we used the assignment operator (=) with a new value we just created another object and now the variable is bound to a new object

Note that x, y and w all got new values inside the function but they are all local to the function so x, y and w outside the function were not modified. It is important to note that x, y, z and w inside the function (local variables) were all pointing to the same objects as x, y, z and w outside the function (global variables) before the modification. Think of x outside and x inside as two different variable names pointing to the same object. After the modification, x outside and x inside are not pointing to the same object any more except in the case of z because in that case we are operating on the same target object using the append operation

Summary

If it is still hard not to think of it in terms of pass by value or reference then I would suggest to think of it as pass by reference all the time as long as you modify the passed object inside the function (ex. z.append) but if you assign it a new value (ex. y = “BAT”) then this is like pass by value because we are essentially creating a new object and assigning it to the local variable copy inside the function.

That is all for today. Please leave a comment if you have questions.

Tags:

Add a Comment

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