The Wayback Machine - https://web.archive.org/web/20240913193306/https://www.geeksforgeeks.org/pass-by-reference-vs-value-in-python/
Open In App

Pass by reference vs value in Python

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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)


Similar Reads

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
5 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definitions and statements. The sys module provides functi
3 min read
Python | Split and Pass list as separate parameter
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let's discuss cert
4 min read
Difference between continue and pass statements in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scop
3 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Python - pass multiple arguments to map function
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
3 min read
Digital Low Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse R
4 min read
Digital High Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital High Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse
5 min read
Digital Band Pass Butterworth Filter in Python
In this article, we are going to discuss how to design a Digital Low Pass Butterworth Filter using Python. The Butterworth filter is a type of signal processing filter designed to have a frequency response as flat as possible in the pass band. Let us take the below specifications to design the filter and observe the Magnitude, Phase & Impulse R
5 min read
Implement Photoshop High Pass Filter (HPF) using OpenCV in Python
In this article, we will discuss how to implement photoshop High Pass Filter (HPF) image in Python OpenCV. High Pass Filter When we talk about Digital Signal Processing or Digital Image Processing Filters are the most fundamental concept. A Filter or a Digital Filter is used to sifting out the unwanted frequency response from the signals. A filter
5 min read
Pass function and arguments from node.js to Python
Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence l
4 min read
How to pass an array to a function in Python
In this article, we will discuss how an array or list can be passed to a function as a parameter in Python. Pass an array to a function in Python So for instance, if we have thousands of values stored in an array and we want to perform the manipulation of those values in a specific function, that is when we need to pass an entire array to the speci
4 min read
Python pass Statement
The Python pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. The Syntax of the pass statementpassWhat is pass statement in Python? When the user does not know what code to write, So user simply places a pass at that line. Sometimes, the pass is
3 min read
Pass Arguments to the Metaclass from the Class in Python
Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metaclass during the class definition. What is a Metacla
3 min read
How to pass optional parameters to a function in Python?
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or ju
5 min read
break, continue and pass in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from their normal sequence. When execution leaves a sc
7 min read
Pass JavaScript Variables to Python in Flask
In this tutorial, we'll look at using the Flask framework to leverage JavaScript variables in Python. In this section, we'll talk about the many approaches and strategies used to combine the two languages, which is an essential step for many online applications. Everything from the fundamentals to more complex subjects, such as how to handle enormo
7 min read
How to Pass Arguments to Tkinter Button Command?
When a user hits the button on the Tkinter Button widget, the command option is activated. In some situations, it's necessary to supply parameters to the connected command function. In this case, the procedures for both approaches are identical; the only thing that has to vary is the order in which you use them. Method 1: Pass Arguments to Tkinter
2 min read
How to Pass Additional Context into a Class Based View (Django)?
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context va
2 min read
How to pass arguments to shell script in crontab ?
In this article, we will discuss how to schedule shell scripts in crontab and to pass necessary parameters as well. First, let's create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run. #! /
2 min read
How to Fix: if using all scalar values, you must pass an index
In this article, we discuss how to fix the error: if using all scalar values, you must pass an index in Python. Cases of this error occurrence: C/C++ Code # Importing pandas library import pandas as pd; # Creating a dictionary or the data to # be converted to the dataframe dict = {'column-1': 1,'column-2': 2, 'column-3': 3,'column-4': 4} # Converti
2 min read
Why do we pass __name__ to the Flask class?
The __name__ is a built-in special variable that evaluates the name of the current module. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name. index.html Let's look at a very basic boi
2 min read
Pass multiple columns in UDF in Pyspark
In this article, we are going to learn how to pass multiple columns in UDF using Pyspark in Python. Pyspark has numerous types of functions, such as string functions, sort functions, Window functions, etc. but do you know Pyspark has also one of the most essential types of functions, i.e., User Defined Function or UDF? UDF is a crucial feature of S
5 min read
How to pass a list as a command-line argument with argparse?
Argparse is a Python library used to parse command-line arguments in a user-friendly manner. It makes it easy to write user-friendly command-line interfaces, and it is widely used in Python applications. In this tutorial, we will discuss how to pass a list as a command-line argument using the Argparse library in Python. Passing a List as a Command
5 min read
How to pass multiple arguments to function ?
A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program.  When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or imple
5 min read
How to Pass a Dictionary to Django Models During Creation
When using Django, a Python web framework, we might need to create models with specific details. A common question is whether we can pass a dictionary to a Django model when creating it. In this article, we will explore if this can be done and what it means for our project. Pass a Dictionary to Django Models using **kwargs In Django, models are obj
2 min read
Python VLC MediaPlayer - Retaining Reference of it
In this article we will see how we can retain reference of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can create a M
2 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 module also provides a container named 'array' for st
4 min read
Practice Tags :