In this lesson, you will learn how to identify when two different variables are actually looking at the exact same object in memory and why that matters for your program.
The "Alias" Effect
In Python, when you assign one variable to another, like y = x, you aren't creating a copy of the object. Instead, you are creating a second "name" (or reference) that points to the same location in memory. Both variables now act as labels for the identical data.
When dealing with mutable objects—like lists—this can lead to surprises. If you change the object using one variable, the other variable will see the change immediately because they are both pointing to the same underlying object.
Observing Shared References
You can verify if two variables share the same reference using the is operator, which we discussed in previous lessons. Let’s see this in action:
# Create a list
a = [1, 2, 3]
# Create a second variable that points to the same object
b = a
# Check if they point to the same memory address
print(a is b) # Output: True
# Mutate the list using 'a'
a.append(4)
# Observe that 'b' reflects the change made via 'a'
print(b) # Output: [1, 2, 3, 4]
In the example above, a and b are effectively aliases for the same list. Because lists are mutable, modifying a affects b. If you were to assign a = [5, 6] later, you would be reassigning a to a new object, breaking the shared reference, while b would continue to point to the original [1, 2, 3, 4] list.
How to Detect Them
To manage your program’s state safely, always remember:
- Use
isto confirm if two variables are bound to the same identity. - If you want two variables to have the same data but remain independent, you must create a distinct copy of the object rather than simply assigning one variable to another.
Key Takeaway: When multiple variables reference the same mutable object, any mutation performed through one variable will be reflected in all other variables pointing to that same object.