How to append elements in Python tuple?

Monday, Aug 5, 2024 | 3 minutes read | Update at Monday, Aug 5, 2024

@ İsmail Baydan

Tuples are used to store multiple elements in a single object. In order to use tuple we generally add, remove elements. Tuples in Python are immutable, meaning once they are created, their contents cannot be changed directly. However, you can create a new tuple that includes the elements of the original tuple along with the new elements you want to add.

Here’s how you can do it:

Using Concatenation

You can concatenate the original tuple with another tuple containing the new elements. In the following example we will sum, concatenate or merge two tupples by using the + operator. The second tuple is defined with the ( ... ).

# Original tuple
original_tuple = (1, 2, 3)

# Element to append
new_element = 4

# Create a new tuple by concatenation
new_tuple = original_tuple + (new_element,)

print(new_tuple)  # Output: (1, 2, 3, 4)

Python do not provides a function like add() to add new elements to the existing tuple.

Using a List Conversion

Tuples provide very similar features and functionality to the lists. We can use list in order to add new elements to the tuple. First you need to convert tuple to the list. You can convert the tuple to a list, append the elements to the list, and then convert it back to a tuple.

# Original tuple
original_tuple = (1, 2, 3)

# Element to append
new_element = 4

# Convert tuple to list
temp_list = list(original_tuple)

# Append the new element
temp_list.append(new_element)

# Convert list back to tuple
new_tuple = tuple(temp_list)

print(new_tuple)  # Output: (1, 2, 3, 4)

Do not forget to convert list to tuple.

Appending Multiple Elements

Some times you may need to add or append multiple elements into the tuple. If you want to append multiple elements, you can use either of the above methods. Following methods are the same with the adding single element to the tuple:

Using Concatenation

As previously described you can use + operator in order to add/append to the tuple.

# Original tuple
original_tuple = (1, 2, 3)

# Elements to append
new_elements = (4, 5)

# Create a new tuple by concatenation
new_tuple = original_tuple + new_elements

print(new_tuple)  # Output: (1, 2, 3, 4, 5)

Using List Conversion

# Original tuple
original_tuple = (1, 2, 3)

# Elements to append
new_elements = [4, 5]

# Convert to list
temp_list = list(original_tuple)

# Extend the list with new elements
temp_list.extend(new_elements)

# Convert back to tuple
new_tuple = tuple(temp_list)

print(new_tuple)  # Output: (1, 2, 3, 4, 5)

By using these methods, you can effectively “append” elements to a tuple in Python.

© 2024 Linux and Python Tutorials

🌱 Powered by Hugo with theme Dream.