Python3: Mutable, Immutable… everything is object!

joel silva
3 min readMay 21, 2021

ID and Type

Two tools that will come in handy throughout this project are ID and Type. According to the official Python documentation, the id() function returns identity (unique integer of an object). This function helps us determine if we’re creating new objects or reusing existing ones. For example:

In this example, we’re creating two variables, a and b, and setting them both to 98. By running id() on them, we can see that they have the same identity. This means that both a and b are pointing to the same instance of 98.

The type() function is used to return the type of object. In this project, we used this command to reveal some interesting behavior with regard to tuples:

In this example, variables a, c, and d are all tuples but variable b is an int. This shows that an empty tuple, a tuple with two integers, and a tuple with one integer followed by a comma are all stored as tuples. However, a single integer between two parentheses will just be stored as an integer.

Mutable Objects

Mutable objects are objects that can be changed. In Python, the only objects that are mutable are lists, sets, and dicts. Take a look at this example:

In this example, a is a list of three integers. We can append the integer 4 to the end of this list. Running the id function before and after appending 4 shows that it is the same list both before and after. We can also use item assignment to change the value of one of the items in our list. I used item assignment to set the value of element #2 to 5. Printing id again shows that we are working on the same list.

Immutable Objects

Immutable objects are objects that cannot be changed. In Python, this would include ints, floats, strings, user-defined classes, and more. These data types cannot be modified. This can be shown in the following example with a string:

We cannot change element #2 in the string “Holberton” to the letter x because strings are immutable. They cannot be changed. Let’s take a look at another example:

In this example, strings a and b are both set to Holberton. Because strings are immutable in Python, they will both point to the same space in memory storing this string. We can test if two strings have the same value using the double equal sign, ==. We can test if two strings refer to the same object using the “is” operator. This tells us that a and b both refer to the same object. This can also be verified by running the id() function on both strings. Because the same string has two different names, the string is said to be aliased.

--

--