= [1, 2, 3]
a 4)
a.append(print(a)
[1, 2, 3, 4]
Python organizes its objects in two ways: they can be mutable, or immutable. A mutable object can be modified after it has been defined, and an immutable object cannot be modified after it has been defined.
Examples of mutable data include: Lists,, Dictionaries, DataFrames, and Series. Examples of immutable data include: Tuples, and actually all the primitive data types, such as String, Integer, Float, Boolean. (If x = 3
, then you can reassign x = 4
, but you are not changing the actual value of 3
.)
There are some interesting properties of mutable objects that we need to pay close attention to, in particular to assigning variables to each other.
In our style of writing code, we have been modifying our objects as we go, like this:
= [1, 2, 3]
a 4)
a.append(print(a)
[1, 2, 3, 4]
However, consider the following pattern in which we assign b
to a
and then perform the append method on b
.
= [1, 2, 3]
a = a
b 4)
b.append(print(b)
[1, 2, 3, 4]
Let’s look at a
also:
print(a)
[1, 2, 3, 4]
Strange, a
was modified also! What’s going on?
When we created the variable a
to equal the list [1, 2, 3]
, it is tempting to say, “the variable ‘a’ is a list with value [1, 2, 3]”, but that is technically incorrect!
The correct way: “the variable ‘a’ is a reference to a list with value [1, 2, 3]”.
We now make a distinction between the variable and the object: the variable gives the reference information to the object, and other variables can reference the same object also! When we evaluated b = a
, we told b
to reference thee same object as a
, so modifying b
modified a
also.
This reference information tells us where the object is stored in the working memory of the computer, usually in the address form of a number.
Let’s see this in action: