A shared reference occurs when multiple variables refer to the same object in memory. Instead of creating a new object during assignment, Python creates another reference to the existing object. Shared references are also needed because changes made to mutable objects, such as lists and dictionaries, can affect all variables that reference the same object.
Example:
x = 5
y = x
print(x)
print(y)
Output
5 5
Reassigning Variables
Reassigning a variable creates a new reference without affecting other variables.
x = 5
y = x
x = "Geeks"
print(x)
print(y)
Output
Geeks 5
Explanation:
- Initially, both x and y reference 5.
- x = "Geeks" creates a new string object.
- x now references "Geeks".
- y still references 5.
If an object is no longer referenced, Python eventually reclaims its memory through garbage collection.
Shared References and Mutable Objects
Mutable objects can be modified after creation. This requires extra care when using shared references.
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]
Explanation:
L2 = L1creates a shared reference.- Both variables point to the same list.
L1[0] = 0modifies the original list in place.- The changes are visible through both variables.
Creating Independent Copies
If separate objects are needed, create a copy instead of a shared reference.
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]
Explanation:
L1[:]creates a shallow copy of the list.L1andL2become independent objects.- Modifying
L1no longer affectsL2.
Note: List slicing only works for lists. Use .copy() for dictionaries and sets.
Comparing Objects Using == and is
Python provides two ways to compare objects.
Example 1: Shared Reference
L1 = [1, 2, 3]
L2 = L1
print(L1 == L2)
print(L1 is L2)
Output
True True
Explanation:
- == compares object values.
- is compares object identities.
- Since both variables reference the same object, both return True.
Example 2: Different Objects With Same Values
L1 = [1, 2, 3]
L2 = [1, 2, 3]
print(L1 == L2)
print(L1 is L2)
Output
True False
Explanation:
- Both lists contain identical values.
- They are stored as separate objects in memory.
- == returns True.
- is returns False.
Small Integer and String Caching
Python internally caches some frequently used immutable objects such as small integers and certain strings to improve performance.
a = 50
b = 50
print(a == b)
print(a is b)
Output
True True
Explanation:
- Python may reuse the same object for small integers.
- a and b can reference the same cached object.
- Therefore, is may also return True.
Note: Object caching is an implementation detail and should not be relied upon in programs. Use == for value comparisons and reserve is for identity checks (for example, value is None).
Assignment vs Copying in Python
| Operation | Creates New Object? | Shared Reference? |
|---|---|---|
b = a | No | Yes |
b = a[:] | Yes (lists only) | No |
b = a.copy() | Yes | No |