Change tuple item in Python
As tuple is immutable collection which does not allows to change value of tuple item once it created. The value of tuple can be changed either by convert the tuple into a list, change the list, and convert the list back into a tuple or merge two tuple using plus operator and assign back to object again.

Change tuple using list

To change element using list object, first convert tuple to list and change element by using index value and convert back to tuple as shown below.
Change tuple using list
 1 tpl = ("apple", "banana", "cherry")
 2 
 3 # converting tuple to list
 4 arr = list(tpl)
 5 arr[1] = "orange"
 6 arr.append("kiwi")
 7 
 8 # converting tuple
 9 tpl = tuple(arr)
 10 
 11 # updated tuple
 12 print("Changed tuple : ", tpl)
In the above example, a tuple is created with initial string values. A list is converted by passing the tuple object that returns a list of specified tuple elements. An existing element is changed by using index value and a new element is appended using append() method.
A tuple object is created by using constructor method by passing list object which create new tuple object and assigning it to the same tuple object and printed on console.
Output
 1 Changed tuples :  ('apple', 'orange', 'cherry', 'kiwi')

Change tuple item using plus operator

A tuple items can also be changes by creating new tuple and merge two tuple by using plus operator.
Change tuple item using plus operator
 1 tpl = ("apple", "banana", "cherry")
 2 
 3 # creating new tuple
 4 arr = ("orange", "kiwi")
 5 # merging two tuple
 6 tpl += arr
 7 
 8 # updated tuple
 9 print("Changed tuple : ", tpl)
In the above example, a tuple object created with string values. A new tuple object is created with two string element and merged into first tuple object by using plus equal operator which will adds all the elements from the two tuples objects. The result will be assigned to the object that will be printed on console.
Output
 1 Changed tuple :  ('apple', 'banana', 'cherry', 'orange', 'kiwi')
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us