Write a Python program to add an item in a tuple


The program is written in Python and performs the following steps:

  • A tuple t is defined with five integers, 10, 40, 50, 70, 90.
  • The value of t is printed to the console.
  • The tuple t is concatenated with another tuple (20,) to create a new tuple t. The trailing comma , is used to indicate that the second tuple is a tuple with a single item.
  • The value of t is printed to the console.
  • The tuple t is converted to a list using the list() function and assigned to a new variable l.
  • The append() method is used to add a new integer 30 to the list l.
  • The list l is converted back to a tuple using the tuple() function and assigned to the variable t.
  • The value of t is printed to the console.

In Python, tuples are immutable, which means that once a tuple is created, its elements cannot be changed. However, it is possible to create a new tuple by concatenating existing tuples. In this program, the original tuple t is concatenated with another tuple to create a new tuple with more items. To add items to a tuple, it must be first converted to a list, and then the list can be modified. The final step converts the list back to a tuple.

Source Code

#create a tuple
t = (10,40,50,70,90) 
print(t)
t = t + (20,)
print(t)
#converting the tuple to list
l = list(t) 
#use different ways to add items in list
l.append(30)
t = tuple(l)
print(t)

Output

(10, 40, 50, 70, 90)
(10, 40, 50, 70, 90, 20)
(10, 40, 50, 70, 90, 20, 30)

Example Programs