How to add elements in Tuple in Python
Tuples are immutable data types in Python. Hence you
- can’t add elements to a tuple because of their immutable property. There’s no
append()
orextend()
method for tuples, - can’t remove elements from a tuple, also because of their immutability. Tuples have no
remove()
orpop()
method,
But there are some ways through which we can add elements in Tuple.
# sample tuple tp = (7, 6, 2, 5, 3, 1) print("Initial tuple: ", tp) # using merge of tuples with the + operator you can add an element and it will create a new tuple tp = tp + (9,) print("After adding 9: ", tp) # adding items in a specific index tp = tp[:5] + (5, 12, 7) + tp[:5] print("Tuple now: ", tp) #converting the tuple to list li = list(tp) #use different ways to add items in list li.append(10) tp = tuple(li) print("Tuple (Tuple->list->tuple): ", tp)
Output:
Initial tuple: (7, 6, 2, 5, 3, 1) After adding 9: (7, 6, 2, 5, 3, 1, 9) Tuple now: (7, 6, 2, 5, 3, 5, 12, 7, 7, 6, 2, 5, 3) Tuple (Tuple->list->tuple): (7, 6, 2, 5, 3, 5, 12, 7, 7, 6, 2, 5, 3, 10)
Subscribe
Login
Please login to comment
0 Discussion