Ladh Mouhamed
3 min readMay 26, 2020

--

Python3: Mutable, Immutable… everything is object!

Introduction

Today’s project for Cohort 11 at Holberton School is different from the ones before it. Instead of building a project, we’re focusing on concepts. Now that we understand that everything is an object, we’re looking more closely at how Python works with different types of objects. We’re looking at specific lines of code and determining how and why they behave the way they do. Instead of submitting programs, we’re submitting text files with one word answers. It would be easy to type all the commands in the Python interpreter, put in the answers, and call it a day. But that would defeat the purpose, which is to understand the reasons behind the answers to these tasks and apply the same logic to other variables

Objects and Values

An object in Python is something you can refer to. Let’s assign some values to a variable. Which essentially means we make var_1 refer to object “Holberton”.

Types & id

The id() function returns the identity of an object as an integer. This corresponds to the location of the object in memory. The function type() returns the type of an object.

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:

Lists are mutable (they can be changed)

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.

Imutable Objects

  • On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range.
# Mutables
my_list = [10, 20, 30]
print(my_list)# [10, 20, 30]my_list = [10, 20, 30]
my_list[0] = 40
print(my_list)# [40, 20, 30]# Immutable
my_yuple = (10, 20, 30)
print(my_yuple)# (10, 20, 30)my_yuple = (10, 20, 30)
my_yuple[0] = 40
print(my_yuple)# Traceback (most recent call last):
File "test.py", line 3, in < module >
my_yuple[0] = 40
TypeError: 'tuple' object does not support item assignment

--

--