Shared Reference in Python
Last Updated :
14 Mar, 2024
Let, we assign a variable x to value 5, and another variable y to the variable x.
Python3
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:
Python3
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:
Python3
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.
Python3
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 ?
Python3
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.
Python3
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.
Python3
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,
Python3
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:
Python3
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read