0

I was going through python language reference and I came across following:

when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.

Am I correct in thinking that tuple can be considered both as mutable and immutable based the things it contains? For example if a tuple contains only strings then it can be immutable and if it contains at least one mutable reference like list then the tuple is itself mutable as.

Ansuman Bebarta
  • 7,011
  • 6
  • 27
  • 44

3 Answers3

5

All a tuple does is contain a fixed list of references. Those references cannot be changed, and so this makes a tuple immutable. Whether the referenced objects are mutable is another story, but that's beyond the scope of tuple, so it would not be accurate to say a tuple can be mutable if it references mutable objects.

FatalError
  • 52,695
  • 14
  • 99
  • 116
1

That's not usually the way it's conceptualized. The tuple is always immutable; the objects it contains may or may not be mutable. Similarly, if you have a fireproof box, and you put paper inside it, the box is still fireproof, even though the paper is not (and thus the entire box-paper combo could be considered non-fireproof).

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

Am I correct in thinking that tuple can be both mutable and immutable based the things it contains?

Consider the fact, that, tuples contains a fixed sized objects with definite identifiers. None of these objects can be replaced with a different object. But this does not mean the object's content cannot change.

Technically speaking if

T = (O1, O2, O3 .. On), where O1 through On are certain objects and through out the lifetime of the tuple T, you cannot replace one or more of these objects Oi with some other objects Oj where i <> j. But Oi can mutate.

Abhijit
  • 62,056
  • 18
  • 131
  • 204