Only two operations are allowed on tuple
, as shown below.
Operations like insert
/ delete
at an index is not allowed. I learnt that tuple
is an immutable data model.
list
allows insert
and delete
operations. I learnt that list
is the mutable data model.
My question:
Is it mutability factor, that does not allow tuple
to perform insert
and delete
operations?
0
Yes. The insert and delete operations change an existing object, rather than creating a new one with a different set of elements. Any type that allows those operations is clearly mutable.
The equivalent of an insert/delete operation for an immutable type like a tuple would be constructing a new tuple that’s only one element different from the original. For instance, >>> tup[0:n] + (x,) + tup[n:]
is sort of like inserting x after element n, and >>> tup[0:n-1] + tup[n+1:]
is sort of like deleting element n.
Why do we care about immutable types? Because they’re less error prone. Consider:
>>> x = 3
// many lines of code that don't mention x
>>> x
=> 3
It seems obvious that if you don’t assign a new value to x, the value of x should not have changed. With immutable types like integers and tuples, this is guaranteed by the language. You can safely make the assumption that no direct changes to x means x has the same value it did when you left it.
With mutable types like tuples, you can’t ever make that assumption.
>>> x = [1, 2, 3]
>>> y = x
>>> x
=> [1, 2, 3]
>>> y.insert(1, 999) // we're not using x here
>>> x
=> [1, 999, 2, 3] // but somehow x changed anyway
This is just a toy example. In very large programs where a mutable variable can potentially be accessed from hundreds or thousands of different places in any order, it’s impossible to keep track of who might be modifying it or expecting who else to modify it at certain times.
This overlaps heavily with the more well-known argument that global variables are evil. Immutable global variables are much less evil.
5
From a theoretical standpoint, yes, the immutability of tuples is the reason for their lack of insert and delete.
More accurately, it is the lack of the implementation of methods for insert and delete that makes tuples immutable since Python uses runtime, duck typing for type checking. You call a method on an object and the object will either reply with the results of that method or it will return an AttributeError.