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:
Uses of OS and Sys in Python
Next article icon

Shared Reference in Python

Last Updated : 14 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Let, we assign a variable x to value 5, and another variable y to the variable x.




x = 5
y = x
 
 

When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python.
Now, if we write:




x = 'Geeks'
 
 

This statement makes a new object to represent ‘Geeks’ and makes x to reference this new object. However, y still references the original object i.e 5. Again if we write one more statement as:




y = 10
 
 

b
This statement causes the creation of a new object and made y to reference this new object. The space held by the prior object is reclaimed if it is no longer referenced, that is, the object’s space is automatically thrown back into the free space pool, to be reused for a future object.
This automatic reclamation of object’s space is known as Garbage Collection.

Shared reference and In- place changes

There are objects and operations that perform in-place object changes. For example, an assignment to an element in a list actually changes the list object itself in-place, rather than creating a new list object. For objects that support in-place changes, you need to be very careful of shared reference, as a change in one can affect others.




L1 = [1, 2, 3, 4, 5]
  
L2 = L1
 
 

Just like x and y, L1 and L2, after statement 2, will refer to the same object. If we change the 0th place value in L1, Now think what will happen, whether it will change only L1 or both L1 and L2 ?




L1 = [1, 2, 3, 4, 5]
L2 = L1
  
L1[0] = 0
  
print(L1)
print(L2)
 
 

Output:

[0, 2, 3, 4, 5]  [0, 2, 3, 4, 5]

Thus, the change in L1 reflects back to L2. Rather than creating a new object for L1, it overwrites the part of the list object at that place. This is an in-place change. If we still want to maintain a separate copy for L2 such that any changes in L1 doesn’t reflect in L2, then we can request Python to create a copy of the list L1 for L2.




L1 = [1, 2, 3, 4, 5]
L2 = L1[:]
  
L1[0] = 0
  
print(L1)
print(L2)
 
 

Output:

[0, 2, 3, 4, 5]  [1, 2, 3, 4, 5]

Note: This slicing technique doesn’t work for dictionaries and sets.

Because of Python’s reference model, there are two different ways to check for equality in Python Program.




L1 = [1, 2, 3, 4, 5]
L2 = L1
  
print(L1 == L2)
print(L1 is L2)
 
 

Output:

True  True

The first method, the == operator tests whether the referenced objects have the same values, if they have the same values, it returns True, otherwise False. The second method, the is operator, instead tests for object identity – it returns True only if both names point to the exact same object, so basically it is a much stronger form of equality testing. It serves as a way to detect shared references in your code if required. It returns False if the names point to an equivalent but different objects.

Now, here comes a tricky part:
Look at the following code,




L1 = [1, 2, 3, 4, 5]
L2 = [1, 2, 3, 4, 5]
  
print(L1 == L2)
print(L1 is L2)
 
 

Output:

True  False

What will happen if we perform the same operation on small numbers:




a = 50
b = 50
  
print(a == b)
print(a is b)
 
 

Output:

True  True

Because small integers and strings are cached and reused, therefore they refer to a same single object. And since, you cannot change integers or strings in-place, so it doesn’t matter how many references there are to the same object.



Next Article
Uses of OS and Sys in Python

S

shubhamkumarlhh
Improve
Article Tags :
  • Python
  • Python Programs
  • python-basics
Practice Tags :
  • python

Similar Reads

  • File Versioning in Python
    In Python, the term "file versioning" usually refers to the process of keeping track of several file versions, frequently recording changes, preserving the past, and promoting cooperation in software development projects. In this article, we will what is file versioning in Python and how we can use
    3 min read
  • How to Change Class Attributes By Reference in Python
    We have the problem of how to change class attributes by reference in Python, we will see in this article how can we change the class attributes by reference in Python. What is Class Attributes?Class attributes are typically defined outside of any method within a class and are shared among all insta
    3 min read
  • Python - Add Set Items
    Python sets are efficient way to store unique, unordered items. They provide various methods to add elements ensuring no duplicates are present. This article explains how to add items to a set in Python using different methods: Add single set item using add() MethodThe add() method allows you to add
    2 min read
  • Uses of OS and Sys in Python
    In this article, we will see where we use Os and Sys in Python with the help of code examples. What is Os Module?Python OS module in Python furnishes a versatile means of engaging with the operating system. It facilitates a range of operations, including the creation, deletion, renaming, movement, a
    4 min read
  • How to copy a string in Python
    Creating a copy of a string is useful when we need a duplicate of a string to work with while keeping the original string intact, strings in Python are immutable which means they can't be altered after creation, so creating a copy sometimes becomes a necessity for specific use cases. Using SlicingSl
    2 min read
  • Python String Input Output
    In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output. Input operations in PythonPython’s input() function allows us to get data from the
    3 min read
  • Understanding the Execution of Python Program
    This article aims at providing a detailed insight into the execution of the Python program. Let's consider the below example. Example: C/C++ Code a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and .py is the e
    2 min read
  • Telnet - Python Network programming
    Telnet is a networking protocol that follows a client-server model. It uses TCP as its underlying communication protocol. It is typically used to start and a remote command-line session, typically on a server. Some facts about telnet:Uses Transmission Control Protocol for data transmission.Bi-direct
    5 min read
  • Run One Python Script From Another in Python
    In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the
    5 min read
  • Differences between Python Parallel Threads and Processes
    In Python, parallelism is a powerful concept used to execute multiple tasks concurrently by improving performance and efficiency. The Two common approaches to parallelism in Python are parallel threads and parallel processes. While both achieve concurrent execution they have distinct characteristics
    3 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