TypeError: 'tuple' object does not support item assignment

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'tuple' object does not support item assignment #

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.

typeerror tuple object does not support item assignment

Here is an example of how the error occurs.

main.py
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.

main.py
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.

This is necessary because tuples are immutable, whereas lists are mutable.

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).

main.py
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.

You can use the 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:

  • Using a pair of parenthesis () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.