Mutable and Immutable Values
A mutation changes an existing object. Rebinding associates a name with another object and can leave older references intact.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Observe a shared list
Take cart = ["tea"] and give a second name preview to the same list. Appending bread through cart makes both names show the second item. Rebinding cart to an empty list leaves preview on the original. The identity check explains why the two observations diverge.
Reason about strings
A Python string is immutable. Repeatedly binding s to a concatenated result leaves other references to the earlier string unchanged. A mutable object contained in an immutable outer container is a separate case. Shallow copying uses this distinction when a nested list may still be shared.[1][2]
Observe mutation through one reference
A list can be modified in place by appending. Imagine a and b both refer to [2, 5]. After a.append(7) they both see [2, 5, 7]. Assigning a new list to a then leaves b on the prior object. For a string, a concatenation such as label = label + "!" binds a name to the resulting text. Earlier names for the underlying string keep their original contents. Bindings and objects explain how the same syntax can read one object and then select another.
Make contracts state what callers can edit
A function returning a list can either expose its own reserved list or return a fresh copy under its contract. A caller sorting the result has a visible effect only if the returned object, or another affected nested object, is shared. Test two calls on the same input and modify the first result in a supported way. Check the second result and original input after that change. For nested values, document which layers allow modifications. A shallow container copy preserves entry references, so it can be suitable for reordering and unsuitable for isolating nested mutations.