TypeError: 'set' object does not support item assignment

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "TypeError: 'set' object does not support item assignment" occurs when we try to change the value of a specific item in a set. If you meant to declare a list, use square brackets instead of curly braces, e.g. my_list = [].

typeerror set object does not support item assignment

Here is an example of how the error occurs.

main.py
my_set = {'a', 'b', 'c'} # ⛔️ TypeError: 'set' object does not support item assignment my_set[0] = 'z'

Set objects are an unordered collection of unique elements, so they don't support indexing and slicing.

If you meant to declare a list, use square brackets instead of curly braces.

main.py
my_list = ['a', 'b', 'c'] # 👇️ update the value of an item at specific index my_list[0] = 'z' print(my_list) # 👉️ ['z', 'b', 'c'] # 👇️ add item to the end of the list my_list.append('d') print(my_list) # 👉️ ['z', 'b', 'c', 'd'] # 👇️ insert item at specific index my_list.insert(0, '.') print(my_list) # 👉️ ['.', 'z', 'b', 'c', 'd']

We changed the value of the list element at index 0.

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.

Lists are an ordered collection of items, so accessing the list at a specific index makes sense.

On the other hand, set objects are unordered collections of unique elements, so they don't have indices.

If you meant to add an item to a set, use the add() method.

main.py
my_set = {'a', 'b', 'c'} my_set.add('d') print(my_set) # 👉️ {'d', 'c', 'b', 'a'}

The set.add method adds the provided element to the set.

You can pass a set object to the list() constructor to convert a set to a list, but since set objects are unordered, running the same code multiple times would produce a list containing the same elements in different order.

main.py
my_set = {'a', 'b', 'c'} my_list = list(my_set) print(my_list) # 👉️ ['a', 'c', 'b'] print(my_list[0]) # 👉️ 'a'

If you meant to declare a dictionary, containing key-value pairs, use the following syntax.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(my_dict['name']) # 👉️ "Alice" print(my_dict['age']) # 👉️ 30

Notice that we separate the keys and values with a colon when declaring a dictionary.

Conclusion #

The Python "TypeError: 'set' object does not support item assignment" occurs when we try to change the value of a specific item in a set. If you meant to declare a list, use square brackets instead of curly braces, e.g. my_list = [].

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.