In Python, tuples are immutable, and elements stored inside the tuple will not be modified, unlike a list. The list is mutable, and the element value of the list is easily modified after its creation. The “tuple object does not support item assignment” TypeError is invoked in the program when the item value of the tuple is changed.
This Python write-up will cover the following contents and discuss various reasons and solutions for “TypeError: tuple object does not support item assignment” with numerous examples:
- Reason: Changing Tuple Item Value
- Solution 1: Convert Tuple Into a List
- Solution 2: Declare List Instead of Tuple
Reason: Changing Tuple Item Value
The prominent reason that invokes the error “tuple object does not support item assignment” is when the user tries to modify the item value of the tuple in a Python program.
The above snippet shows the TypeError when the tuple value is changed.
Solution 1: Convert Tuple Into a List
To resolve “TypeError”, the tuple value is converted into a list value using the built-in “list()” function. The list is mutable, unlike a tuple. So, the element value is easily replaced by accessing the index number.
tuple_value = ('Alex', 'Binny', 'Cyndy') list_value = list(tuple_value) list_value = 'Zach' tuple_value = tuple(list_value) print(tuple_value)
In the above code, the tuple is first converted into a list, and after that, the element of the list is changed using an index. After successfully changing the list element, the updated value has been converted back to a tuple.
The tuple’s new item value, “Zach”, has been replaced by the old value, “Binny”, in the above output.
Solution 2: Declare List Instead of Tuple
The very efficient way to handle this error is using list data type for storing multiple values instead of tuples at the start of the program. Because using a list data type allows the user to change the element value at any time in the program.
list_value = ['Alex', 'Binny', 'Cyndy', 'Lily'] print('Original list',list_value) list_value = 'David' print('\nUpdate list',list_value)
In the above code, the “list_value” is initialized and the element of the list is replaced by accessing the index.
Note: If you want your answer in a tuple, then the “tuple()” function is utilized in the program to convert the list into a tuple.
The above output shows the original list and the updated list.
That’s it from this guide!
In Python, the “tuple object does not support item assignment” error arises when the user tries to change a tuple’s element/item value. To resolve this “TypeError”, the tuple value is converted into a list using the “list()” function, and the item’s value is changed using the specific index. After changing the items on the list, you may convert the list back into tuples. This post presented various reasons and solutions for the “tuple object does not support item assignment” TypeError in Python.