Understanding Super Basics Of Immutability in Python
Photo by Hitesh Choudhary on Unsplash

Non member? (Click)

Have you ever tried to change a character in a Python string and encountered an error you didn’t quite understand?

Well, We all have been there.

:)

Why can’t I just update this letter?

The answer lies in Python’s design philosophy around immutability.

Now, What is Immutability in Python?

In Python, some objects are immutable, meaning their contents can’t be changed after creation.
Instead of modifying them, Python creates a new object altogether.
“Think of an immutable object like a sealed envelope. If you want to update the letter inside, you can’t — you’ll need to create a new envelope with the new letter.”

(Stole this from a stack overflow answer I read years ago lol)

Examples?

Strings, tuples, integers, and floats.

Now, let’s get into: Strings: The Immutable Trouble Spot

my_string = "shashwat"
my_string[0] = "S" # This throws an error -> TypeError: 'str' object does not support item assignment

Python complains because strings are immutable. You can’t change individual characters directly.

So, how to “update” a string correctly:

my_string = "S" + my_string[1:]

Simple enough?

Another bro who is immutable? Our very own → tuple

my_tuple = (1, 2, 3)
my_tuple[0] = 0 #errorrrrrrrrrrrr!

But hey, not lists!

my_list = ["h", "e", "l", "l", "o"]
my_list[0] = "H" # This works fine!
Once you learn this, you realize immutability isn’t a limitation — it’s a design choice to keep Python programs more predictable and bug-free.

Umm how?

Thread safe: Immutable objects can safely be shared across threads. Or you know your first and your sixty ninth thread might change your string’s ‘i’th index in a way, corrupting it?

Since immutable objects cannot be changed, there’s no risk of one thread modifying an object while another thread is reading it :)

Btw, remember to use,

tools like .replace() or slicing for strings. Okay?

In case we are meeting for the first time, come over here, it’ll be worth the roller coaster of articles that are gonna come up in the next few weeks.