Daily Dose of Data Science

Share this post

You Were Probably Given Incomplete Info About A Tuple's Immutability

www.blog.dailydoseofds.com

Discover more from Daily Dose of Data Science

High-quality insights on Data Science and Python, along with best practices — shared daily. Get a 550+ Page Data Science PDF Guide and 450+ Practice Questions Notebook, FREE.
Over 37,000 subscribers
Continue reading
Sign in

You Were Probably Given Incomplete Info About A Tuple's Immutability

Let's correct it!

Avi Chawla
Apr 13, 2023
15
Share this post

You Were Probably Given Incomplete Info About A Tuple's Immutability

www.blog.dailydoseofds.com
2
Share

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!

Share Daily Dose of Data Science


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.

15
Share this post

You Were Probably Given Incomplete Info About A Tuple's Immutability

www.blog.dailydoseofds.com
2
Share
Previous
Next
2 Comments
Share this discussion

You Were Probably Given Incomplete Info About A Tuple's Immutability

www.blog.dailydoseofds.com
Don Eaton
Apr 15Liked by Avi Chawla

Great post. Love the enlightening snippets. Keep them coming.

Expand full comment
Reply
Share
Ripunjoy Goswami
Jul 31

Love these articles!! Thank you so much for collating them!!

Expand full comment
Reply
Share
Top
New
Community

No posts

Ready for more?

© 2023 Avi Chawla
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing