Is a tuple, that includes a list actually mutable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is a tuple, that includes a list actually mutable?

I saw a checklist type quiz. It asked to choose all the mutable objects from a list. There was a tuple with list as item. I included it, because it's inner element can be changed and thus mutable, that caused the result to be wrong. I later checked the right answers and it was not selected as right answer. Is the quiz or I wrong? Is an immutable iterator with mutable item mutable or immutable?

11th Mar 2019, 1:11 PM
Seb TheS
Seb TheS - avatar
5 Answers
+ 3
The tuple itself is not mutable, no. If you change the list within, you have not touched the tuple so it all checks out. I see you have done some C and C++, it may be helpful to think about the inner list as a pointer. The tuple only holds the pointer and doesn't really care about what is happening with the mutable content that is being pointed to.
11th Mar 2019, 1:25 PM
Schindlabua
Schindlabua - avatar
+ 4
I've created a code, you can experiment with it..... https://code.sololearn.com/c1ln32A7tFkE/?ref=app
11th Mar 2019, 6:58 PM
Ayush Sinha
Ayush Sinha - avatar
+ 1
Tuples are immutable whatever elements they contain. How the immutable tuple can contain a mutable item? It is a result of memory management in Python. In simple words any variable is a reference to the object in Python. So the tuple store a reference to the list. When the list changes ths reference stays the same.
11th Mar 2019, 1:39 PM
portpass
+ 1
portpass You can't for example include immutable iterators with mutable items as dictionary keys.
11th Mar 2019, 1:41 PM
Seb TheS
Seb TheS - avatar
+ 1
Seb TheS Yes, the same thing with sets. And there's a reason for that. Python calculates hashes of the dictonary keys to quick access to the dictionary. These hashes must not be changeable for dictonary keys.
11th Mar 2019, 4:28 PM
portpass