Python

TypeError: ‘tuple’ object does not support item assignment ( Solved )

Tuples, lists, maps are data structures in python. All of them are used for creating multiple items in a single variable. But they have different features. Some support item assignment and some not. In this entire tutorial you will know how to solve the TypeError ‘tuple’ object does not support item assignment.

What are tuples ?

Tuples are used to create multiple elements in a single variable. It is just like list but instead of the square bracket it uses round brackets. Once the tuple is created you cannot change  the value of the elements. Therefore it is immutable.

The syntax for the list is the below.

sample_tuple  = (element1,element2,element,...)

What cause ‘tuple’ object does not support item assignment error

In case you are manipulating the tuple object and you are getting the tuple’ object  item assignment error. Then most of the case it is due to that you are changing the elements of the tuple.

Lets take an example and creat this error.

Suppose I have tuple with name of the three students in it. I want to change the name of the third student. And if I use the below lines of code then I will get the ‘tuple’ object does not support item assignment error.

sample_tuple = ("Sahil","Bob","Robin")
sample_tuple[2] = "Maya"

Output

object does not support item assignment error

Solution for ‘tuple’ object does not support item assignment error

There is a trick for solving  this error. As you already know the tuple object is immutable. Once  the elements for the tuples are defined, you can’t change it. But list object elements can be changed.

Therefore if you want to change any elements of the tuples then you have to first convert it into list. After that change the element of the lists. Finally if you want to again get the tuple then you have to  change the list to the tuple.

Execute the below lines of code to change the element of the tuple.

sample_tuple = ("Sahil","Bob","Robin")
demo_list = list(sample_tuple)
demo_list[2] ="Maya"
sample_tuple = tuple(demo_list)
print(sample_tuple)

Output

Changing the element of the tuple

Conclusion

‘tuple’ object does not support item assignment is a TypeError that you will get when you try to change the element of the tuple object. As tuple is immutable, before changing elements you have to first convert it into list and then change the elements.

The above method works without giving you error and change the element of tuple.

If you have any query then you can contact us for more help.