Assignments vs Mutations
Assignments bind variables to objects, a process implemented via the =
operator. For instance, x = 3
and x = [1,2,3]
are examples of assignments, where 3
and [1,2,3]
represent the objects being assigned to x
.
Mutations, by contrast, modify the elements of an object, without creating a new one. These operations also rely on the =
operator, with x[1] = 0
being an example of mutation.
Despite sharing the same operator =
, assignments and mutations are conceptually distinct. This difference can be better appreciated by visualizing objects as specific memory addresses. This implies that assignments like x = [4,5]
involve two steps: i) finding a memory location to store the object with value [4,5]
, and ii) labeling the memory address as x
for easy access. In contrast, a mutation modifies the contents of the object, but without changing its memory address.
To illustrate this, consider the example x = [4,5]
, where the object [4,5]
is stored in a particular memory location. If you then run x = [6,7]
, x
becomes associated with a new object containing [6,7]
, thus constituting an assignment. However, if you execute x[1] = 0
afterwards, the operation modifies the original object [6,7]
to [6,0]
. This operation constitutes a mutation because x
continues to reference the same memory address, even though its content has changed.
MUTATION
ASSIGNMENT
Remark You can mutate all the elements of
x
, without this necessarily entailing a new assignment. For example, this occurs when we modify the values of
x
by mutating
x[:]
.
The distinction is particularly important since mutations tend to be faster than creating new objects. This will become relevant in Part II, where we explore strategies for speeding up operations.