Modifying Elements of a Tuple

It is not possible to modify or update an element of a tuple since tuples are immutable. If we want to modify the element of a tuple, we have to create a new tuple with a new value in the position of the modified element. Let's take 'x' is the existing tuple and 'y' is the new tuple.

First of all, copy the elements of 'x' from 0th position to pos-2 position into 'y' as:

y = x[0:pos-1]

Concatenate the new element to the new tuple 'y'. Thus the new element is stored in the position of the element being modified.

y = y+new

Now concatenate the remaining elements from 'x' by eliminating the element which is at 'pos-1'. It means we should concatenate elements from 'pos' till the end. The total tuple can be assigned again to the old name 'x'.

x = y+x[pos:]


modifying elements

A Python program to modify or replace an existing element of a tuple with a new element.