Add and Remove Element in Python Tuple Tutorial

In this section, we will learn how to add or remove elements to a tuple object in Python.

Python Tuple Append

A tuple object is immutable! Which means we can’t add or remove an element from a tuple object.

But we know that a tuple object is an iterable object! So one thing we can do is to convert the tuple object into another data type like a List because using a list object we’re free to modify the elements there and after the modification, convert the target list back into a tuple object.

Note: we use the `list()` function to convert a tuple object into a list object. Also, we use `tuple()` function to convert a list object into a tuple object.

Example: appending to tuple in python

tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly")

list1 = list(tup1)

list1.append("Maya")

list1.append("Bill")

tup1 = tuple(list1)

print(tup1)

Output:

('Ellen', 'Jack', 'Omid', 'Elon', 'James', 'Richard', 'Jeremy', 'Ian', 'Kimberly', 'Maya', 'Bill')

Example: removing item from python tuple

tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly")

list1 = list(tup1)

list1.pop(0)

list1.pop(1)

list1.pop(4)

tup1 = tuple(list1)

print(tup1)

Output:

('Jack', 'Elon', 'James', 'Richard', 'Ian', 'Kimberly')

Leave a Reply