Mutable and Immutable objects in Python

Member-only story

Pythons Mutable & Immutable Objects

Carlos Esquivel
4 min readJan 13, 2021

Python is an object-oriented language that boasts many rules that are sometimes confusing. One thing in particular is the nature of how mutable and immutable objects behave in Python. To first understand what mutable and immutable objects are we to understand that everything in Python is an object, which is either immutable or mutable(unchangeable, or changeable). This means that every object in Python has an individual object id that corresponds to it at runtime.

Immutable objects

In Python, an object is either mutable or immutable object(bool, int, float, etc…) or a mutable object(list, set, dict). To understand these classes we must first learn about id() and type().

In python the corresponding id is printable with the built-in id() function which returns an integer that is the corresponding place in memory. The type() function is used to return the class of an object.

''' Example for id()'''
>>> a = "Cat"
>>> b = "Cat"
>>> id(a)
4500500848 # number in memory
>>> id(b)
4500500848 #number in memory
>>> print(x is y)
True
=======================
''' Example 2 '''
>>> a = [1, 2, 3]
>>> type(a)
<class: ‘list’>
>>> b = "cat"
>>> type(b)
<class: 'string'>

--

--

No responses yet