Python Object Types: Mutable and Immutable


We know how to assign names to objects of various classes, but can we change their value?

It turns out, yes and no! Some classes are considered Immutable, while others are mutable.

Before we talk about the differences between the two, we’ll discuss how we can find the type and id of an object.

id and type:


id is a built-in function in module builtins; it returns the identity of an object. This number is the object’s memory address and is unique.

>>> a = “Hello”
>>> id(a)

If two names refer to the same object, they will have the same id:

>>> a = “hi”
>>> b = “hi”
>>> b is a
>>> id(a)
>>> id(b)


When passed an object or name of an object, `type` returns the type of the object.

>>> a = 1
>>> type(a)
<class ‘int’>

mutable objects:

If an object’s contents can change, it is considered mutable.

Objects that refer to the following classes are mutable:
Format: [1, 2, 3]
Cloning: modify a list and keep a copy of the original

>>> a = [1, 2, 3]
>>> b = a[ : ]
>>> b = b.append(4)
>>> print b
[1, 2, 3, 4]
>>> print a
[1, 2, 3]

Format: {‘key1’ : ‘value1’, ‘key2’ : ‘value2’}

>>> my_dict = { ‘Greatest Hit’ : ‘Song’}
>>> my_dict(‘Best Album’) = ‘Album’
>>> my_dict
{‘Best Album’ : ‘Album’, ‘Greatest Hit’ : ‘Song’}

Immutable objects:

An object is considered immutable if its contents cannot be changed.

To optimize resources, Python makes two names that refer to the same immutable value (such as a string) refer to the same object.

Objects that refer to the following classes are immutable:

Strings: “Hello, World!”
Integers: 1
 Format: {1, 2, 3} or set()
*Special Tuple Note*: Tuples are immutable, but they can hold a value that is mutable. For example:

>>> t = (1, 2, [4, 5])
>>> t[2] += [6]
>>> t
(1, 2, [4, 5, 6])

Why does it matter and how differently does Python treat mutable and immutable objects:

If two names have the same value and are immutable, Python has them both refer the same object.

Comparatively, if the object have the same value but are mutable, they do not refer to the same object.

Test if two name have the same value == :

>>> a = “Holberton”
>>> b = “Holberton”
>>> a == b

Test if two names refer to the same object: is operator

>>> a = “Holberton”
>>> b = “Holberton”
>>> a is b

How objects are passed to functions and what does it imply for mutable and immutable objects:

All objects are passed to functions by calling a function and entering the object’s name as a parameter of the function.

/Bonus Content/


When the same object has two different names. If changes are made to one alias, the other is also affected.

>>> a = [1, 2, 3]
>>> b = a # make an alias of a named b
>>> a is b # Do a and b refer to the same object?
True # Answer: They do!
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.