Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: 'tuple' object does not support item assignment" occurs when we try to change the value of an item in a tuple. To solve the error, convert the tuple to a list, change the item at the specific index and convert the list back to a tuple.
Here is an example of how the error occurs.
my_tuple = ('a', 'b', 'c') # ⛔️ TypeError: 'tuple' object does not support item assignment my_tuple[0] = 'z'
It isn't possible to assign to individual items of a tuple, so we have to convert the tuple to a list first.
my_tuple = ('a', 'b', 'c') # 👇️ convert tuple to list my_list = list(my_tuple) print(my_list) # 👉️ ['a', 'b', 'c'] # 👇️ update item my_list[0] = 'z' # 👇️ convert list back to tuple my_tuple = tuple(my_list) print(my_tuple) # 👉️ ('z', 'b', 'c')
We used the list()
class to convert a tuple into a list.
Once we have a list, we can update the item at the specific index and optionally convert the result back into a tuple.
Alternatively, you can declare a list from the beginning by wrapping the elements in square brackets (not parenthesis).
my_list = ['a', 'b', 'c'] my_list[0] = 'z' print(my_list) # 👉️ ['z', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['z', 'b', 'c', 'd'] my_list.insert(0, '.') print(my_list) # 👉️ ['.', 'z', 'b', 'c', 'd']
Declaring a list from the beginning is much more efficient if you have to change the values in the collection often.
Tuples are intended to store values that never change.
append()
method to add an item to the end of the list or the insert()
method to add an item at a specific index.In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructor