Open In App

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.

Understanding Tuples

Before we dive into appending elements to tuples, permit’s quick evaluation of what tuples are and why they’re beneficial. Tuples are ordered collections of items, and they could hold gadgets of different types, similar to lists. Here’s how you create a tuple in Python:



my_tuple = (1, 2, 3, 'apple', 'banana')

Here, we have a tuple like my_tuple, you cannot change its values directly. However, you can create a new tuple with additional elements by following a few different methods.

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.






original_tuple = (1, 2, 3)
new_element = 4
 
appended_tuple = original_tuple + (new_element,)
print(appended_tuple)

Output
(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.




original_tuple = (1, 2, 3)
new_element = 4
 
original_tuple += (new_element,)
print(original_tuple)

Output
(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.




original_tuple = (1, 2, 3)
new_element = 4
 
appended_tuple = original_tuple + (new_element,)
print(appended_tuple)

Output
(1, 2, 3, 4)




Article Tags :