Tuple is Immutable

Now, let’s try doing the same things to a tuple. We know that a tuple is immutable, so some of these operations shouldn’t work. We’ll take a new tuple for this purpose.

>>> mytuple=0,1,2,3,4,5,6,7

First, let’s try reassigning the second element.

>>> mytuple[1]=3

Traceback (most recent call last):

File “<pyshell#70>”, line 1, in <module>

mytuple[1]=3

TypeError: ‘tuple’ object does not support item assignment

As you can see, a tuple doesn’t support item assignment.

However, we can reassign an entire tuple.

>>> mytuple=2,3,4,5,6

>>> mytuple

(2, 3, 4, 5, 6)

Next, let’s try slicing a tuple to access or delete it.

>>> mytuple[3:]

(5, 6)

>>> del mytuple[3:]

Traceback (most recent call last):

File “<pyshell#74>”, line 1, in <module>

del mytuple[3:]

TypeError: ‘tuple’ object does not support item deletion

As is visible, we can slice it to access it, but we can’t delete a slice. This is because it is immutable.

Can we delete a single element?

>>> del mytuple[3]
Traceback (most recent call last):

File “<pyshell#75>”, line 1, in <module>

del  mytuple[3]

TypeError: ‘tuple’ object doesn’t support item deletion

Apparently, the answer is no.

Finally, let’s try deleting the entire tuple.

>>> del mytuple

>>> mytuple

Traceback (most recent call last):

File “<pyshell#77>”, line 1, in <module>

mytuple

NameError: name ‘mytuple’ is not defined

So, here, we conclude that you can slice a tuple, reassign it whole, or delete it whole.

But you cannot delete or reassign just a few elements or a slice.

Let us proceed with more differences between python tuples vs lists.


Posted on by