When we say tuples are immutable, many Python programmers think that the values inside a tuple cannot change. But this is not true.
The immutability of a tuple is solely restricted to the identity of objects it holds, not their value.
In other words, say a tuple has two objects with IDs 1 and 2. Immutability says that the collection of IDs referenced by the tuple (and their order) can never change.
Yet, there is NO such restriction that the individual objects with IDs 1 and 2 cannot be modified.
Thus, if the elements inside the tuple are mutable objects, you can indeed modify them.
And as long as the collection of IDs remains the same, the immutability of a tuple is not violated.
This explains the demonstration above. As
append is an inplace operation, the collection of IDs didn't change. Thus, Python didn't raise an error.
We can also verify this by printing the collection of object IDs referenced inside the tuple before and after the append operation:
As shown above, the IDs pre and post append are the same. Thus, immutability isn’t violated.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day.
👉 Read what others are saying about this post on LinkedIn.
👉 Tell me you liked this post by leaving a heart react ❤️.
👉 If you love reading this newsletter, feel free to share it with friends!
Find the code for my tips here: GitHub.
I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.
Great post. Love the enlightening snippets. Keep them coming.