How to remove elements from a tuple in Python

In this tutorial, we will learn how to remove elements from a tuple in Python.

A tuple is a list of immutable objects. In other words, the elements in a tuple cannot be modified or changed throughout the program. But, what if we need to modify a given tuple in a program?

Removing elements from a tuple in Python

In order to remove elements from any tuple, we need to slice the tuple. Let us take an example,

# Declare a tuple
a = ( 23, 56, 76, 90, 18 )

Suppose, we want to delete 76 from the given tuple. So, the index n of the element to be removed is 2. Hence, we will slice the tuple from (0 to n-1) to (n+1 to end).

a = ( 23, 56, 76, 90, 18 )

n=2
# slicing from 0 to n-1
a[:n]
# slcing from n+1 to end
a[n+1:]

After slicing the tuple, we then add the two sliced tuples together. As a result, the nth element gets removed from the tuple, since it was in neither of the two sliced parts.

a = ( 23, 56, 76, 90, 18 )

n=2
# slicing from 0 to n-1
a[:n]
# slcing from n+1 to end
a[n+1:]

# Combining the two parts
a = a[:n] + a[n+1:]

print("The modified tuple is",a)

Output:

The modified tuple is (23, 56, 90, 18)

Thus, we have successfully managed to remove the nth element from the given tuple. Suppose we wanted to remove two elements from the tuple.

a = ( 23, 56, 76, 90, 18 )

n=2
# slicing from 0 to n-1
a[:n]
# slcing from n+2 to end
a[n+2:]

# Combining the two parts
a = a[:n] + a[n+2:]

print("The modified tuple is",a)

Output:

The modified tuple is (23, 56, 18)

Hence, two elements have been removed from the tuple by changing the sliced tuples.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *