Python tuples are immutable right?

Tuples are immutable, unchangeable right? Well yes – sort of. The issue is easier to illustrate than describe so here goes. If we have a list, we can add new items. E.g.

>>> l = ["apple", "banana", "cucumber"]
>>> l
['apple', 'banana', 'cucumber']
>>> l.append("date")
>>> l
['apple', 'banana', 'cucumber', 'date']

If we have a tuple, we can’t change which objects are contained in the tuple:

>>> t = ("apple", "banana", "cucumber")
>>> t
('apple', 'banana', 'cucumber')
>>> t[3] = "date"

You get TypeError: ‘tuple’ object does not support item assignment

So once you have a tuple, nothing will change, right? It is even called immutable so end of story right? Not quite.

Well try this:

>>> a = ["apple",]
>>> b = ["banana",]
>>> c = ["cucumber",]
>>> t = (a,b,c)
>>> t
(['apple'], ['banana'], ['cucumber'])
>>> b.append("A new banana in my immutable tuple! WAT?!")
>>> t
(['apple'], ['banana', 'A new banana in my immutable tuple! WAT?!'], ['cucumber'])

From the official documentation:

“Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.)” (Data Model) [emphasis added]

Subtle – yes – well said. Which objects are contained in a tuple is fixed – but what those objects are is not. In practice, most tuples are containers of numbers and strings and this potential confusion never arises. Incidentally, even though tuples are immutable, they can’t be used dictionary keys if they contain mutable objects. Try it! E.g.

d = {((1,2), (3,4)): 100}
vs
d = {((1,2), [3,4]): 100}

For more useful explanation of how Python handles variables, objects etc check out: Drastically Improve Your Python: Understanding Python’s Execution Model. It sometimes introduces too many new ideas at once in the example code but is very helpful if you focus on the salient parts of the examples only.

[Added later] See Python tuples: immutable but potentially changing