Appending Elements to a Tuple
Using the + Operator
In this example, we create a new tuple appended_tuple by concatenating the original_tuple with a tuple containing the new element. Note the comma after new_element.
Python3
original_tuple = ( 1 , 2 , 3 ) new_element = 4 appended_tuple = original_tuple + (new_element,) print (appended_tuple) |
(1, 2, 3, 4)
Using the += Operator
In this case, original_tuple is reassigned to a new tuple created by concatenating the original tuple with a tuple containing the new element. While this code achieves the desired result, it can be confusing because it may appear that the original tuple is being modified in place when, in fact, it’s not. To maintain clarity, it’s better to use the + operator as shown earlier.
Python3
original_tuple = ( 1 , 2 , 3 ) new_element = 4 original_tuple + = (new_element,) print (original_tuple) |
(1, 2, 3, 4)
Using the tuple() Constructor
It is less efficient than using the + operator, especially when dealing with large tuples, because it involves creating new objects.
Python3
original_tuple = ( 1 , 2 , 3 ) new_element = 4 appended_tuple = original_tuple + (new_element,) print (appended_tuple) |
(1, 2, 3, 4)
How to append elements in Python tuple?
In this article, we will explore how to append elements to a tuple in Python. Appending elements to a tuple in Python may additionally seem counterintuitive due to the immutability of tuples.