Python Tuple Operations


Add Items

As tuples are immutable, so there is no way we can directly add items to the tuple. But we do have a workaround to do so, by converting a tuple to a list and then add an item and again convert back to a tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist.insert(2, "Tom")

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Steve', 'Tom', 'Tim')

Change/Update item

As tuples are immutable, so it is not possible even to change item of tuple, but again we can use the workaround of converting tuple to list, change the items of list and convert the list back to tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist[2] =  "Tom"

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Steve', 'Tom')

Remove Items

Again, because tuples are immutable, so we cannot even remove an item from a tuple. To achieve this, we can use the same workaround of converting tuple to list, remove item and then again converting it back to tuple.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
namelist = list(nametuple)

namelist.remove("Steve")

nametuple = tuple(namelist)
print(nametuple)
('Bill', 'Tim')

Join Tuples

We simply use the + operator to join tuples.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
newnames = ("Tom", "Sam")

nametuple = nametuple + newnames
print(nametuple)
('Bill', 'Steve', 'Tim', 'Tom', 'Sam')

Delete a tuple

We use del keyword to delete a tuple.

Once the tuple is deleted, we get the NameError saying “name ‘nametuple’ is not defined”.

In [1]:
nametuple = ("Bill", "Steve", "Tim")
del nametuple
print(nametuple)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c9b88b96c9c5> in <module>
      1 nametuple = ("Bill", "Steve", "Tim")
      2 del nametuple
----> 3 print(nametuple)

NameError: name 'nametuple' is not defined