Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Maksym Ivashchenko
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 = []
.
Here is an example of how the error occurs.
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.
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
.
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.
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.
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.
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.