Pass by reference vs value in Python
Last Updated :
09 Aug, 2024
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 are the causes of 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
Python’s argument-passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”.
Depending on the type of object you pass in the function, the function behaves differently. Immutable objects show “pass by value” whereas mutable objects show “pass by reference”.
You can check the difference between pass-by-value and pass-by-reference in the example below:
Python
def call_by_value(x):
x = x * 2
print("in function value updated to", x)
return
def call_by_reference(list):
list.append("D")
print("in function list updated to", list)
return
my_list = ["E"]
num = 6
print("number before=", num)
call_by_value(num)
print("after function num value=", num)
print("list before",my_list)
call_by_reference(my_list)
print("after function list is ",my_list)
Output
number before= 6
in function value updated to 12
after function num value= 6
list before ['E']
in function list updated to ['E', 'D']
after function list is ['E', 'D']
In the above code, we have shown how Python uses call by reference object concept in its program.
We pass an integer in function call_by_value(). Integers are immutable objects hence Python works according to call by value, and the changes made in the function are not reflected outside the function.
We then pass list to function by reference. In function call_by_reference() we pass a list that is an mutable object. Python works according to call by reference in this function and the changes made inside the function can also be seen outside the function.
The variable is not the object
Here “a” is a variable that points to a list containing the elements “X” and “Y”. But “a” itself is not a 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 means 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 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.
Pass by Reference In Python Example
In this example, the function modify_list takes a list by reference. The function adds the string “Geeks” to the passed list inside the function and prints it. Since lists are mutable data types, the changes made to the list inside the function are also reflected outside the function as you can see in the output.
Python
def modify_list(x):
x.append("Geeks")
print("Inside function:", x)
my_list = ['Geeks', 'for']
modify_list(my_list)
print("Outside function:", my_list)
Output
Inside function: ['Geeks', 'for', 'Geeks']
Outside function: ['Geeks', 'for', 'Geeks']
What is Pass by Value In Python?
In this approach, we pass a copy of the actual variables in the 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.
Pass by Value In Python Example
Here, we will pass the integer x to the function which is an immutable data type. We then update the value of the integer inside the function and print the updated value. The changes are not seen outside the function as integers are immutable data types.
Python
def modify_integer(x):
x = x + 10
print("Inside function:", x)
x = 5
print("Before function call:", x)
modify_integer(x)
print("After function call:", x)
Output:
Before function call: 5
Inside function: 15
After function call: 5
Python programming uses “pass by reference object” concept while passing values to the functions. This article tries to show you the concept of pass by value and pass by reference in Python. We have shown different cases of passing values with examples. Passing values to a function in Python is different from other coding languages, but with this tutorial, you can easily understand the concept and implement it in your work.
Also Read:
Is Python call by reference or call by value
Pass by reference vs value in Python – FAQs
Is Python pass by reference or value?
Python uses a mechanism known as “pass by object reference” or “pass by assignment“. This means that when you pass a variable to a function, you are passing the reference to the object (or value) the variable points to. However, this reference itself is passed by value.
What is the difference between pass by value and pass by reference?
- Pass by Value:
- A copy of the actual data (value) is passed to the function.
- Changes made to the parameter inside the function do not affect the original data.
- Used in languages like C, C++ for primitive types.
- Pass by Reference:
- A reference (memory address) to the original data is passed to the function.
- Changes made to the parameter inside the function affect the original data.
- Used in languages like C, C++ for non-primitive types and objects.
Does Python pass string by reference or value?
In Python, strings are passed by object reference. When you pass a string to a function, you are passing a reference to the string object. Changes made to the string inside the function can affect the original string if mutable operations are performed (like modifying in-place).
Example:
def modify_string(s):
s += " World" # This creates a new string object
my_string = "Hello"
modify_string(my_string)
print(my_string) # Output: Hello (unchanged)
Why is pass by reference better than pass by value?
- Efficiency: Pass by reference avoids making copies of large data structures, which can be more efficient.
- Mutability: It allows functions to modify complex objects (like lists, dictionaries) directly, without needing to return them.
- Consistency: It maintains consistency in behavior when dealing with mutable objects.
What is the difference between call by value and call by reference in Python?
In Python, the terms “call by value” and “call by reference” are not used directly due to the way parameters are passed:
- Call by Value: In Python, when you pass an immutable object (like integers, strings) to a function, a copy of the object’s value is passed. Modifications to the parameter inside the function do not affect the original object.
- Call by Reference: In Python, when you pass a mutable object (like lists, dictionaries) to a function, a reference to the original object is passed. Modifications to the parameter inside the function affect the original object.
Example:
def update_list(lst):
lst.append(4) # Modifies the original list
my_list = [1, 2, 3]
update_list(my_list)
print(my_list) # Output: [1, 2, 3, 4] (original list is modified)
Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today
Similar Reads
Pass by reference vs value 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 are the causes of the confusion at the fundamental level. In the article, we will be discu
7 min read
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.
5 min read
Weak References in Python
Python's memory management algorithm uses a reference counting mechanism for garbage collection, which tracks all reachable objects. All Python objects include a reference count field, which counts how many objects are referencing it. If an object is referenced by another object, then its counter is
4 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
str() vs repr() in Python
In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object. Python str()
3 min read
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Python dictionary values()
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get "dict_values object". It must be cast to obtain the actual list. Python Dictionary valu
2 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
range() vs xrange() in Python
The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
How to Reference Elements in an Array in Python
Prerequisites: Numpy Elements of an array can be referenced like a regular python array. Since python internally doesn't support arrays, here whenever we use the term array we are referring to pythons list that can be used to build an array of any required dimension. Besides this, Python's NumPy mod
4 min read
Python List VS Array VS Tuple
List: A list is of an ordered collection data type that is mutable which means it can be easily modified and we can change its data values and a list can be indexed, sliced, and changed and each element can be accessed using its index value in the list. The following are the main characteristics of
3 min read
Role of Underscores '_' in Python
The Underscore (_) is an eccentric character in Python. It can be used in many ways in a Python program. The various uses of underscore (_) in Python are: 1) Use in Interpreter: Python immediately saves the value of the last expression in the interpreter in this unique variable. Underscore (_) can a
3 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store
3 min read
reflection in Python
Reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to a function. For example, if we write type(obj) then Python will return an object which represents the type of obj. Using reflection, we can write one recursive reverse funct
3 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements
3 min read
Python pass Statement
Pass statement in Python is a null operation or a placeholder. It is used when a statement is syntactically required but we don't want to execute any code. It does nothing but allows us to maintain the structure of our program. Example Use of Pass Keyword in a FunctionPass keyword in a function is u
3 min read
Scope Resolution in Python | LEGB Rule
Here, we will discuss different concepts such as namespace, scope, and LEGB rule in Python. What are Namespaces in Python A python namespace is a container where names are mapped to objects, they are used to avoid confusion in cases where the same names exist in different namespaces. They are create
5 min read
Global and Local Variables in Python
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only insid
7 min read
Python: Key Value pair using argparse
The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Steps For Using Argpa
2 min read