In this article we will discuss how to Append, Insert, Replace and Delete elements from a tuple in python.

In Python, tuples are immutable i.e. once created we can not change its contents.  But sometimes we want to modify the existing tuple, in that case we need to create a new tuple with updated elements only from the existing tuple.
Let’s see how to insert, modify and delete the elements from tuple.

Append an element in Tuple at end

Suppose we have a tuple i.e.

Now to append an element in this tuple, we need to create a copy of existing tuple and then add new element to it using + operator i.e.

We will assign the new tuple back to original reference, hence it will give an effect that new element is added to existing tuple.
Contents of tuple will be now,

A new Element is appended at the end of tuple.

Insert an element at specific position in tuple

To insert an element at a specific index in the existing tuple we need to create a new tuple by slicing the existing tuple and copying contents from it.

Suppose we have a tuple i.e.

As indexing starts from 0 in tuple, so to insert an element at index n in this tuple, we will create two sliced copies of existing tuple from (0 to n) and (n to end) i.e.

Now join these two sliced copies with new elements in between i.e.

Now contents of tuple will be.

A new Element is inserted at index n.

Modify / Replace the element at specific index in tuple

To replace the element at index n in tuple we will use the same slicing logic as above, but we will slice the tuple from from (0 to n-1) and (n+1 to end) i.e.

None of the above sliced copies contains existing element at index n. Now join these two sliced copies with new elements in between i.e.

Now contents of tuple will be.

Element in index n is replaced now.

Delete an element at specific index in tuple

To delete the element at index n in tuple we will use the same slicing logic as above, but we will slice the tuple from from (0 to n-1) and (n+1 to end) i.e.

None of the above sliced copies contains existing element at index n. Now join these two sliced copies i.e.

Now contents of tuple will be.

Element in index n is deleted now.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.