Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
callable() in Python
Next article icon

Is Python call by reference or call by value

Last Updated : 14 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

What is Call By Reference in Python?

In Python, "call by reference" is a way of handing arguments to functions where the reference to the real object gets passed instead of the object's actual value. This means that if you make changes to the object within the function, those changes directly affect the original object outside the function. It's important to highlight that this approach in Python is not the same as the traditional "call-by-reference" used in some other programming languages. Python follows its own model, often called "pass-by-object-reference," emphasizing the passing of references to objects while maintaining its unique characteristics.

What is Call By Value in Python?

In Python, the common way of passing function arguments is through "call by value." This means that when you pass a variable to a function, you're essentially handing over the actual value of the variable itself, not the reference to the object it's pointing to. Consequently, any changes made to the variable within the function don't directly affect the original variable outside the function. This approach is consistent with the principles of "call by value" and sets it apart from the "call by reference" mechanisms seen in some other programming languages. In simpler terms, the function deals with a copy of the variable's value, ensuring that the original variable remains unchanged in the broader context of the program.

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 = "GeeksforGeeks"     print("Inside Function:", string)  # Driver's code test(string) print("Outside Function:", string) 

Output
Inside Function: GeeksforGeeks 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) 

Output
Inside Function [10, 20, 30, 40, 50] Outside Function: [10, 20, 30, 40, 50]

Binding Names to Objects

Example 1: Variable Identity and Object Equality in Python

In Python, each variable to which we assign a value/container is treated as an object. When we are assigning a value to a variable, we are actually binding a name to an object.

Python3
a = "first" b = "first"  # Returns the actual location # where the variable is stored print(id(a))  # Returns the actual location # where the variable is stored print(id(b))  # Returns true if both the variables # are stored in same location print(a is b) 

Output
140081020184240 140081020184240 True

Example 2: List Identity and Object Equality in Python

In this example, the Python code compares the memory addresses (locations) of two list variables, a and b, using the id() function. Despite having identical values, the is keyword evaluates to False, indicating that these lists are distinct objects in memory, highlighting the importance of memory address comparison for object identity in Python.

Python3
a = [10, 20, 30] b = [10, 20, 30]  # return the location # where the variable # is stored print(id(a))  # return the location # where the variable # is stored print(id(b))  # returns false if the # location is not same print(a is b) 

Output
140401704219904 140401704222464 False

Example 3: Immutable Objects and Function Parameter Behavior in Python

In this example, the Python code demonstrates the immutability of strings by passing the variable string to the function foo(). Despite attempting to assign a new value inside the function, the original string remains unchanged outside its scope, illustrating that string variables are immutable in Python.

Python3
def foo(a):      # A new variable is assigned     # for the new string     a = "new value"     print("Inside Function:", a)  # Driver's code string = "old value" foo(string)  print("Outside Function:", string) 

Output
Inside Function: new value Outside Function: old value

Example 4: Mutable Objects and In-Place Modification in Python Functions

When we pass a mutable variable into the function foo and modify it to some other name the function foo still points to that object and continue to point to that object during its execution. 

Python3
def foo(a):     a[0] = "Nothing"  # Driver' code bar = ['Hi', 'how', 'are', 'you', 'doing'] foo(bar) print(bar) 

Output
['Nothing', 'how', 'are', 'you', 'doing']

Next Article
callable() in Python

P

priyanshid1
Improve
Article Tags :
  • Python
  • python-basics
Practice Tags :
  • python

Similar Reads

  • Python Dictionary Pass by Value/Reference
    In Python, dictionaries are passed by reference, not by value. Since dictionaries are mutable, passing them to a function means the original dictionary can be modified. If we want to avoid changes to the original, we can create a copy before passing it. Understanding this behavior is key to managing
    3 min read
  • 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
  • callable() in Python
    In this article, we will see how to check if an object is callable in Python. In general, a callable is something that can be called. This built-in method in Python checks and returns True if the object passed appears to be callable, but may not be, otherwise False. Python callable()In Python, calla
    3 min read
  • call() decorator in Python
    Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modifie
    3 min read
  • Assign Function to a Variable in Python
    In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
    4 min read
  • __call__ in Python
    Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When this method is defined, calling an object (obj(arg1, arg2)) automatically triggers obj._
    4 min read
  • Returning a function from a function - Python
    In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior. Example: [GFGTABS] Python def fun1(name): def fun2(): return f"Hello, {name}!"
    5 min read
  • Python __repr__() magic method
    Python __repr__() is one of the magic methods that returns a printable representation of an object in Python that can be customized or predefined, i.e. we can also create the string representation of the object according to our needs. Python __repr__() magic method Syntax Syntax: object.__repr__() o
    4 min read
  • What is the difference between __init__ and __call__?
    Dunder or magic methods in Python are the methods having two prefixes and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. In this art
    3 min read
  • First Class functions in Python
    First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences