It seems counter intuitive that two orthogonal concepts like mutability and type are entangled instead of having some way of mutable qualifying types, like in other languages.
Wouldn't it benefit performance if strings and numbers could be mutable by choice and perform replacements and arithmetic/bit operations in place instead of creating a new object for the result every time?
It occurred to me that maybe it is that way (immutable strings and numbers) to promote functional style programming, but Python is not meant to be a functional programming language.
This question is not about what is mutability/immutability or their pros and cons.
Best How To :
Mutability/immutability is not just a performance matter. Mutating an object means that all references to the object see the change. For some types, this would lead to very odd behavior:
n = number_of_items
# do some stuff. . .
n -= 1
# now the variable number_of_items was changed in the enclosing scope!
Such behavior already suprises some people when it comes to mutable types like lists, but it would be even more surprising for numeric types, since people expect that, e.g., the number 3 cannot change its value.
Moreover, immutability (or at least immutability of the hash-relevant data) is necessary for hashability. Being able to mutate strings would mean you could no longer use them as dictionary keys. You could say that only immutable strings could be used as dictionary keys, but that in effect creates a type split.
The duck-typing philosophy of Python means types are basically defined by what they do. If two objects differ in something as basic as mutability, you can't really use them the same way, so it doesn't make sense to consider them the same type, even if they nominally are. Likewise, there is little practical difference between having one type with mutable and immutable variants, versus having two types that vary in mutability --- e.g., having mutable and immutable lists vs having
tuple as separate types.