Are tuples really immutable?💡

In Python, containers like lists are mutable, while tuples are considered to be immutable.

Let’s take a look at the code in the image. We define a tuple with some elements.

Now if you try to change an element, Python will throw an error saying that < ‘tuple’ object does not support item assignment >.:bulb:

Now, if we append new elements to it, it doesn’t throw an error. Why so?:thinking:

Doing that appending operation essentially creates a new tuple object altogether, which is evident from their different IDs.

Alright, what if we then make changes to the list within that tuple?

It still doesn’t throw any error, and the ID of the tuple is also the same! :confused:

So does this mean tuples can be mutable? No.

The Python containers, such as tuples, contain the references to the elements rather than those elements themselves.

So, when we change the elements of the list, we are actually not changing the tuple. We are just changing the list.:bulb:

And the tuple will still contain the reference to that list, which will still be the same, hence immutable.

Have you come across such instances?

#python #datascience