Variables and Memory · Lecture 08 · 9 min
Shared References and Mutability
When two names point at the same object, mutating it through one name is visible through the other.
What is a shared reference?
A shared reference is when two or more names refer to the same object:
my_var_1 = 'hello'
my_var_2 = my_var_1
print(hex(id(my_var_1)), hex(id(my_var_2)))With an immutable string, sharing is harmless. “Changing” my_var_2 really re-binds it to a new string:
my_var_2 = my_var_2 + ' world!'
print(my_var_1, hex(id(my_var_1)))
print(my_var_2, hex(id(my_var_2)))Shared references to mutable objects
With mutable objects you must be careful:
my_list_1 = [1, 2, 3]
my_list_2 = my_list_1 # same list, second name
my_list_2.append(4)
print('my_list_2:', my_list_2)
print('my_list_1:', my_list_1)
print(hex(id(my_list_1)), hex(id(my_list_2)))append through either name changes the single shared object.There is only one list, and we gave it two names. If you want an independent list, make a copy: my_list_2 = my_list_1.copy() or list(my_list_1). (Copying, including shallow vs deep copies, is covered in Part 2.)
Behind the scenes: Python shares immutable objects for you
Remember this from the lesson on re-assignment?
a = 10
b = 10
print(hex(id(a)), hex(id(b)))The memory manager is free to create shared references to immutable objects on its own, because it’s completely safe: there’s no way to change a’s object through b. The only thing you can do to b is re-bind it:
b = 15
print(hex(id(a)), hex(id(b)))For mutable objects, Python never does this, because it would not be safe:
my_list_1 = [1, 2, 3]
my_list_2 = [1, 2, 3]
print(hex(id(my_list_1)), hex(id(my_list_2)))Same contents, two different objects. Appending to one won’t touch the other.
Key takeaways
- Assigning one variable to another (
b = a) creates a shared reference, not a copy. - Mutating a shared mutable object is visible through every name that refers to it.
- Python may share immutable objects automatically (safe), but never mutable ones.