Tuples are immutable collection of objects. They are similar to a list
but has fewer built-in methods and once initialized, it cannot be changed.
There are several methods to insert a new element into a tuple in python. Go through the following methods and use whichever is suitable for your application.
1, Converting into a list and inserting
In this method, we will first convert the tuple into a list using the list()
class and then use the list.insert()
method to insert the new element into the list. After inserting the element we can convert the list back to a tuple using the tuple()
class.
Steps to perform this method:
- Convert the tuple to a list using the
list()
class. - Insert the element using the
list.insert()
method. - Convert the list back to a tuple using the
tuple()
class.
The above code will result in the following output:
2, Adding a new tuple to an existing tuple
We can create a new tuple by adding a new element as another tuple to the existing one using the addition operator (+).
The above code will give the output as:
Using this technique, we can insert a new element at both the front and the back end of a tuple.
We wrapped the new element in parathesis and added a trailing comma inorder to distinguish it as a tuple instead of a string.
The trailing comma is very significant in the representation of a tuple as it is what differentiates between a string and a tuple.
A tuple can also be made using the tuple()
constructor, where we can convert a sequence like lists and dictionaries into tuples.
Using the tuple()
constructor in the above code yields the output as:
3, Using the "reassignment" operator
Alternatively, we can use the reassignment operator (+=) to add a new element to the same tuple. See the following code:
This will output the result as:
This comes in handy when you don't need to have access to the original tuple, thereby avoiding the need to declare a new variable.
4, Unpacking an existing tuple into a new tuple
When creating a new tuple, we can unpack an existing tuple inside it. This allows us to manipulate the location of the new element or elements up to a certain degree.
This code will output as:
Conclusion
There is no direct method to add an element to a tuple. This is because tuples are immutable collection of objects unlike lists or dictionaries. However, we can manipulate and add elements in multiple ways as we have discussed in this article. These methods will be adequate to handle most of the use cases in your application.
If you found this article useful, feel free to checkout other featured articles in my blog. See you in the next one.