Intermediate 8 min
Value copies and shared references
Two variables can refer to the same object, so a change through one name can appear through the other.
How it works
Make a diagram with names on one side and objects on the other. If two arrows reach the same list, they will both see an item added to it. Change one arrow to point to an entirely new list and the other arrow stays where it was.
Walk through an example
If two labels point to the same shopping list, adding a book through either label changes that list. A shallow copy creates a different outer list but can share nested values.
What to watch for
Reassigning a name and mutating the object it refers to are different operations. Trace which object each name points to.
Check your understanding
Which outer list shows the added value?
See the example and explanation
- Worked example
- Given
Two outer lists share an inner list. Append to the inner list. - Answer
Both.
They both still refer to the same inner list, which was changed in place.