In this tutorial, we’ll learn how to easily add items in Python tuple. We’ll be going through 2 methods and explaining both of them step by step with proper examples so you can have a better idea of how to properly add items in Python tuple.
Introduction: 2 Methods To Add Items In Python Tuple
These 2 methods are listed below:
In the first method, we’ll begin with converting tuple into a Python list. Then we’ll use the append method of Python list to add new items. Finally, we’ll convert back that list into a Python tuple.
Whereas the second method specifies the concatenation/joining two tuples.
Let’s now practically discuss both these methods using multiple examples.
Method 1: Converting Tuple into Python List
See below steps on how to properly use this method:
A simple Python tuple is created having some items.
Tuple is converted into a Python list.
New item has been added to the existing list using Python list append method.
Python list converted again to a tuple.
So this is how we can easily add items in Python tuple. See below output:
(2, 3, 5, 'Purple', 34.6, 33) // old tuple (2, 3, 5, 'Purple', 34.6, 33, 'Orange') // new tuple with item added to it
Method 2: Concatenation of Python Tuples
Second method is just joining two tuples. See below example:
tuple1=(2,3,5,'Purple',34.6,33) tuple2=('Green',[7,8,9.5],9876) newTuple= tuple1 + tuple2 // tuple joined with each other print(newTuple)
(2, 3, 5, 'Purple', 34.6, 33, 'Green', [7, 8, 9.5], 9876)
So these are the two ways/methods through which we can easily add items in Python tuple. Do try it with other examples to grasp a detailed knowledge of how to add items in Python tuple.
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly add items in Python tuple. I’d be very happy to receive your feedback on this post. Thank you for reading it.