Are Tuples really immutable? #PyTip03

Tuple in Python are immutable Data Structures. Unlike sets, dicts and lists, the values in a tuple cannot be changed once initialized.

But is it really the case for tuples? See, tuples are immutable for the contents they hold that means the references of the objects inside the tuple cannot be changed. But what if we change the contents of the without changing the object references.

To see it in action look at the below code

>>> p = 7
>>> id(7)
2917349484976
>>>p = 8
>>>id(p)
2917349485008

In the above code when we changed the value of an integer p the id of the object changed, that means the variable p started to point any other memory location. Now look at the below code.

>>> a = [1,2,3]
>>> id(a)
2917355980416
>>> a.append(4)
>>> id(a)
2917355980416
>>> a += [3,4,5]
>>> id(a)
2917355980416

In the above code we can see that even if we modify our list the id of the list reamains same, which means our variable a still points to the same memory location. We can exploit this behaviour to make our tuple immutable.

Type the below code to make a mutable tuple.

>>> tup = (1,2,[3])
>>> tup
(1, 2, [3])
>>> tup[2]
[3]
>>> tup[2].append(4)
>>> tup
(1, 2, [3, 4])

You can see that since the list object held its id even after we appended 4 to it, so the tuple had no problem mutating itself. The int data structure in Python changes its reference once its value is changes that is why we cannot change integer value in a tuple.

>>> tup[0] = 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Thanks for reading, Hope you liked it.

0
Subscribe to my newsletter

Read articles from Vivek Kumar Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vivek Kumar Singh
Vivek Kumar Singh