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

by | Programming, Python, Tips

In Python, integers are single values. You cannot access elements in integers like you can with container objects. If you try to change an integer in-place using the indexing operator [], you will raise the TypeError: ‘int’ object does not support item assignment.

This error can occur when assigning an integer to a variable with the same name as a container object like a list or dictionary.

To solve this error, check the type of the object before the item assignment to make sure it is not an integer.

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


TypeError: ‘int’ 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 'int' object tells us that the error concerns an illegal operation for integers.

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

Integers are single values and do not contain elements. You must use indexable container objects like lists to perform item assignments.

This error is similar to the TypeError: ‘int’ object is not subscriptable.

Example

Let’s look at an example where we define a function that takes a string holding a phrase, splits the string into words and then stores the counts of each word in a dictionary. The code is as follows:

def word_count(string):

   # Define empty dictionary

   word_dict = {}

   # Split string into words using white space separator

   words = string.split()

   # For loop over words

   for word in words:

   print(word)

   # Try code block: if word already in dictionary, increment count by 1

       try:

           if word_dict[word]:

               value = word_dict[word]

               word_dict = value + 1

   # Except code block: if word not in dictionary, value is 1

       except:

           word_dict[word] = 1

    return word_dict

We will then use the input() method to take a string from the user as follows:

string = input("Enter a string: ")
word_count(string)

Let’s run the code to see what happens:

Enter a string: Python is really really fun to learn

Python
is
really
really
fun

TypeError                                 Traceback (most recent call last)
<ipython-input-15-eeabf619b956> in <module>
----> 1 word_count(string)

<ipython-input-9-6eaf23cdf8cc> in word_count(string)
      9         word_dict = value + 1
     10     except:
---> 11       word_dict[word] = 1
     12 
     13   return word_dict

TypeError: 'int' object does not support item assignment

The error occurs because we set word_dict to an integer in the try code block with word_dict = value + 1 when we encounter the second occurrence of the word really. Then when the for loop moves to the next word fun which does not exist in the dictionary, we execute the except code block. But word_dict[word] = 1 expects a dictionary called word_dict, not an integer. We cannot perform item assignment on an integer.

Solution

We need to ensure that the word_dict variable remains a dictionary throughout the program lifecycle to solve this error. We need to increment the value of the dictionary by one if the word already exists in the dictionary. We can access the value of a dictionary using the subscript operator. Let’s look at the revised code:

def word_count(string):

   # Define empty dictionary

   word_dict = {}

   # Split string into words using white space separator

   words = string.split()

   # For loop over words

   for word in words:

       print(word)

   # Try code block: if word already in dictionary, increment count by 1

       try:

           if word_dict[word]:

               value = word_dict[word]

               word_dict[word] = value + 1

   # Except code block: if word not in dictionary, value is 1

       except:

           word_dict[word] = 1

     return word_dict
Enter a string: Python is really really fun to learn
Python
is
really
really
fun
to
learn

{'Python': 1, 'is': 1, 'really': 2, 'fun': 1, 'to': 1, 'learn': 1}

The code runs successfully and counts the occurrences of all words in the string.

Summary

Congratulations on reading to the end of this tutorial. The TypeError: ‘int’ object does not support item assignment occurs when you try to change the elements of an integer using indexing. Integers are single values and are not indexable.

You may encounter this error when assigning an integer to a variable with the same name as a container object like a list or dictionary.

It is good practice to check the type of objects created when debugging your program.

If you want to perform item assignments, you must use a list or a dictionary.

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