In Python, a tuple is an immutable sequence, meaning once created, its elements cannot be changed, added, or removed. However, you can update tuples indirectly by creating new ones through concatenation, slicing, or converting them to lists.
The concatenation operator + joins two tuples to form a new tuple.
# Original tuple
T1 = (10, 20, 30, 40)
# Tuple to be concatenated
T2 = ('one', 'two', 'three', 'four')
# Updating the tuple using concatenation
T1 = T1 + T2
print(T1)
Output:
(10, 20, 30, 40, 'one', 'two', 'three', 'four')
Slicing allows you to create a new tuple with additional elements.
# Original tuple
T1 = (37, 14, 95, 40)
# Elements to be added
new_elements = ('green', 'blue', 'red', 'pink')
# Updating using slicing
updated_tuple = T1[:2] + new_elements + T1[2:]
print(updated_tuple)
Output:
(37, 14, 'green', 'blue', 'red', 'pink', 95, 40)
Convert a tuple to a list, update it, and convert it back.
# Original tuple
T1 = (10, 20, 30, 40)
# Convert to list and update using list comprehension
updated_tuple = tuple([item + 100 for item in list(T1)])
print(updated_tuple)
Output:
(110, 120, 130, 140)
Convert a tuple to a list, use append(), and convert back.
# Original tuple
T1 = (10, 20, 30, 40)
# Convert tuple to list
list_T1 = list(T1)
# Append new elements
new_elements = [50, 60, 70]
for element in new_elements:
list_T1.append(element)
updated_tuple = tuple(list_T1)
print(updated_tuple)
Output:
(10, 20, 30, 40, 50, 60, 70)
