+ 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?
5 odpowiedzi
+ 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.
+ 4
I've created a code, you can experiment with it.....
https://code.sololearn.com/c1ln32A7tFkE/?ref=app
+ 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.
+ 1
portpass You can't for example include immutable iterators with mutable items as dictionary keys.