How to add new items to tuple in Python
Tuples are immutable data structures in Python, so we can not add or delete the items from the tuples created in Python like lists there is no append() or extend() function.
As per the topic, we cannot add items in the tuples but here are some methods to add items in tuples like converting the tuple into a list or using a ‘+ ‘ operator, etc.
Let’s discuss some methods to add items in the tuple:
- Using ‘+’ operator: As we know tuples are immutable data structures and we can not directly add items to it, so by creating a variable or directly adding value using ‘+’ operator will do the work of adding the single item in tuple, following block of code will make a clear understanding.
tuple1 = ('mango','orange') a ='banana' tuple1 = tuple1 +(a,) print(tuple1)
Output:
('mango', 'orange', 'banana')
- Converting tuple to list for adding more than one items:
This is a very useful method to add more than one item in Python tuples, let’s take a look at following code.tuples = ('mango','orannge') list1 = ['banana','apple','watermelon'] #converting tuple to list a = list(tuples) #adding the items for x in list1: a.append(x) #converting the list again into a tuple a = tuple(a) print(a)
Output:
So we did our tusk successfully.
I hope, you learned something new from this article. Thank you for reading…
Leave a Reply