How to Solve Python TypeError: ‘set’ object does not support item assignment

by | Programming, Python, Tips

In Python, you cannot access the elements of sets using indexing. If you try to change a set in place using the indexing operator [], you will raise the TypeError: ‘set’ object does not support item assignment.

This error can occur when incorrectly defining a dictionary without colons separating the keys and values.

If you intend to use a set, you can convert the set to a list, perform an index assignment then convert the list back to a tuple.

This tutorial will go through how to solve this error and solve it with the help of code examples.


TypeError: ‘set’ object does not support item assignment

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.

The part 'set' object tells us that the error concerns an illegal operation for sets.

The part does not support item assignment tells us that item assignment is the illegal operation we are attempting.

Sets are unordered objects which do not support indexing. You must use indexable container objects like lists to perform item assignment

Example #1: Assigning Items to Set

Let’s look at an example where we have a set of numbers and we want to replace the number 10 with the number 6 in the set using indexing.

numbers_set = {1, 2, 3, 4, 5, 10, 7}

numbers_set[5] = 6

print(numbers_set)

Let’s run the code to see the result:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-f30ce7c96c23> in <module>
      1 numbers_set = {1, 2, 3, 4, 5, 10, 7}
      2 
----> 3 numbers_set[5] = 6
      4 
      5 print(numbers_set)

TypeError: 'set' object does not support item assignment

We throw the TypeError because the set object is indexable.

Solution

To solve this error, we need to convert the set to a list then perform the item assignment. We will then convert the list back to a set. However, you can leave the object as a list if you do not need a set. Let’s convert the list using the list() method:

numbers_set = {1, 2, 3, 4, 5, 10, 7}

numbers_list = list(numbers_set)

print(numbers_list)
[1, 2, 3, 4, 5, 7, 10]

The number 10 is the last element in the list. We can access this element using the indexing operator with the index -1. Let’s look at the item assignment and the conversion back to a set:

numbers_list[-1] = 6

numbers_set = set(numbers_list)

print(numbers_set)

Let’s run the code to get the result:

{1, 2, 3, 4, 5, 6, 7}

We successfully replaced the number 10 using item assignment.

Example #2: Incorrectly Defining a Dictionary

The error can also occur when we try to create a dictionary but fail to use colons between the keys and the values. Let’s look at the difference between a set and a dictionary creation. In this example, want to create a dictionary where the keys are countries and the values are the capital city of each country:

capitals = {"England", "London", "France", "Paris", "Spain", "Madrid","Switzerland", "Zurich"}

We see that we set the capital of Switzerland set incorrectly to Zurich instead of Geneva. Let’s try to change the value of Switzerland using indexing:

capitals["Switzerland"]="Geneva"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-5c3a039dfccf> in <module>
----> 1 capitals["Switzerland"]="Geneva"

TypeError: 'set' object does not support item assignment

We throw the error because we defined a set and not a dictionary. Let’s print the type of the capitals object:

print(type(capitals))
<class 'set'>

We cannot index sets and therefore cannot perform item assignments.

Solution

To solve this error, we need to define a dictionary instead. The correct way to define a dictionary is to use curly brackets {} with each key-value pair having a colon between them. We will also verify the type of the object using a print statement:

capitals = {"England": "London", "France":"Paris", "Spain": "Madrid","Switzerland":"Zurich"}

print(type(capitals))
<class 'dict'>

Now we have a dictionary we can perform the item assignment to correct the capital city of Switzerland. Let’s look at the code:

capitals["Switzerland"]="Geneva"

print(capitals)

Let’s run the code to see what happens:

{'England': 'London', 'France': 'Paris', 'Spain': 'Madrid', 'Switzerland': 'Geneva'}

We correctly updated the dictionary.

Summary

Congratulations on reading to the end of this tutorial. The TypeError: ‘set’ object does not support item assignment occurs when you try to change the elements of a set using indexing. The set data type is not indexable. To perform item assignment you should convert the set to a list, perform the item assignment then convert the list back to a set.

However, if you want to create a dictionary ensure that a colon is between every key and value and that a comma is separating each key-value pair.

For further reading on TypeErrors, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨