Mutability and Objects in Python3

On How Everything is an Object in Python’s World

Image for post
Image for post
The language I’m currently wrangling with
>>> # Example of instantiating an int object
>>> a = 1
>>> type(a)
<class 'int'>
>>> string1 = "Hemant"
>>> type(string1)
<class 'str'>
>>> # Demonstrating the use of a string method on the object "Hemant"
>>> string1.upper()
>>> a = 1
>>> b = 1
>>> a is b
>>> a == b
>>> id(a)
>>> id(b)

Mutable Objects

Objects can come in two flavors: Mutable and Immutable. On a basic level, the difference lies in the ability to be transformed. Mutable objects can be changed whereas immutable objects are frozen after instantiation. Take for example the list, modifying the list’s elements or the size of the list is permissible by the interpreter. Initializing the list with specific values and changing the list elements at a later time won’t cause any exceptions to be raised by the interpreter.

>>> my_list = [1, 2, 3]
>>> my_list[2] = 5
>>> my_list
[1, 2, 5]

Immutable objects

Objects of this kind are not capable of being changed. At the time of instantiation, values that were placed in the object are frozen. Instantiating a generic string and subsequently attempting to modify the string is not possible with objects of this type.

>>> string1 = "Hemant"
>>> string1[2] = 'c'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> # This same traceback is seen when attempting to assign value in an immutable object like a tuple

Why does it matter and how does Python treat mutable vs immutable objects?

Mutability is significant because multiple names can be bound to specific objects in memory. Depending on the specific situation, having a mutable type would also affect all its references which can lead to issues. For example, strings couldn’t be used as keys in dictionaries if they were mutable. Immutable types give you the guarantee that modifications to the underlying object are not permissible.

How are arguments passed to functions and what does that imply for the mutability of objects?

Python functions are Call-By-Object-Reference, meaning the mutability of the object affects the function’s behavior. Types that are immutable are passed by value and don’t make any changes to the underlying object. Mutable objects are passed by reference so the modification of the underlying object is possible.

Written by

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store