{:check ["true"]}
Python maintains data in memory which are referenced by variables.
Consider the following statement:
x = "Hello world"
The memory model looks like this.
+-------------+
x ---> | Hello world |
+-------------+
Python strings are immutable. Namely, there is no way to modify the
content of the data referenced by x
.
If we want to change the string x = "Hello"
, we have to create a new string
and update the reference.
+-------------+
x -+ | Hello world |
| +-------------+
|
| +-------+
+--> | Hello |
+-------+
Python supports mutable lists.
Consider:
x = [1, 2, 3]
y = x
The memory model looks like Figure 1.
y
|
|
| +---+---+---+
+----->| | | |
| 1 | 2 | 3 |
x ---->| | | |
+---+---+---+
Unlike strings, if we want to change the value of x
, Python
allows in-place modification of x
.
x[0] += 10
This makes an in-place modification:
y
|
|
| +----+---+---+
+----->| | | |
| 11 | 2 | 3 |
x ---->| | | |
+----+---+---+
Note that the side effect of x[0] += 10
is that y
also gets updated.
>>> y
[11, 2, 3]