Modify Tuple Elements in Python

In Python, tuples are immutable, so you cannot directly modify elements in a tuple. However, you can achieve similar functionality by using the following methods:

  1. Convert a tuple to a list, modify the elements in the list, and then convert the list back to a tuple.
tup = (1, 2, 3, 4, 5)
lst = list(tup)
lst[2] = 10
tup = tuple(lst)
print(tup)  # Output: (1, 2, 10, 4, 5)
  1. Please rephrase the following sentence in your own words.
tup = (1, 2, 3, 4, 5)
index = 2
new_element = 10
tup = tup[:index] + (new_element,) + tup[index+1:]
print(tup)  # Output: (1, 2, 10, 4, 5)

Both methods involve creating a new tuple rather than modifying the original tuple.

bannerAds