Mutable, Immutable… everything is object!

Working with Python3

Juliana Monroy
2 min readSep 30, 2020

Python is an object oriented programming language. An object is simply a collection of data and methods that act on those data.

We can think of class as a house. It contains all the things inside of it, the doors, floors, windows, rooms, etc. Based on this we build the house. House is the object.

Adicional to this we have to make clear that Mutable types can be changed in place. Immutable types can not change in place.

But how can we know if our variable if Immutable?

Here we have some specific guide for that:

So we can say that our Mutable variables are:

Lists, Set, Dictionary.

Quick example for Mutable will be like…

l1 = [1, 2, 3]
l2 = l1
l1.append(4)
print(l2)

Output:

[1, 2, 3, 4]

and Immutable:

Numbers, Strings and Tuples.

Quick example for Immutable:

>>> str = "OJMP"
>>>id(str)
4702125
>>> str[0]
'O'
>>> s[0] = "A"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

We conclude that the previous string is immutable. You can not change its content. It because this will raise a TypeError if you try to change it.

Types and Id

The id() unction accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime.

>>> a
[1, 2, 3]
>>> id (a)
139926795932424

The type of an object is itself an object and return the type of an object Therefore, the type can be compared using the is operator. All type objects are assigned names that can be used to perform type checking. Most of these names are built-ins, such as list, dict, and file. For example:

if type(l) is list:
print ‘Yei a list’
if type(f) is file:
print ‘Yei a file’

--

--