Typefully

Understanding Mutable and Immutable Elements in Tuples

Avatar

Share

 • 

2 years ago

 • 

View on X

Yesterday I talked about tuples when they're used as dictionary keys Tuples are immutable But their contents don't have to be… Let's look at this tuple `book_entry` which contains an integer, a couple of strings, and a list as its elements twitter.com/s_gruppetta_ct/status/1678690650160791552
The tuple and its elements are separate objects which have their own unique id The tuple is immutable. This means the tuple with the id shown above will always have the same four objects within it, the ones with the ids also shown in the above code snippet
But, the fourth of those elements is a list, which is mutable So, can we still change the contents of the list even though it's a member of an immutable object? Yes. In fact, there are three volumes in this series of books, the third was published in 1965:
Compare the ids of the tuple and the list, which is an element in the tuple, before and after the change to the list… They're both the same objects as before. The same tuple contains the same list, but the list has changed! Lists are mutable, so they can change:
So, in some ways, the tuple has changed too. It's no longer the same as it was before even though it contains the same objects But there's another omission in this entry. Although these three volumes are Feynman's lectures, the books have two more authors Let's add them
We can't Because the third entry in the tuple, the one with the author name, is a string. And strings are immutable
The only way we can modify this is to create a new tuple with the modified values. But if we do this, we're not changing the tuple, we're replacing it with a new one
Because this tuple contains a list, you cannot create a hash value from it The error message shows you that the list is the culprit in this case! You can see why being hashable or not is relevant in yesterday's post: twitter.com/s_gruppetta_ct/status/1678690650160791552
You'll see all of this and more discussed in an article coming soon on The Python Coding Stack open.techwriters.info/thepythoncodingstack
Avatar

Stephen Gruppetta

@s_gruppetta_ct

Constantly looking for innovative ways to talk and write about Python • Mentoring learners • Writing about Python • Writing about technical writing