TypeError: 'int' object does not support item assignment

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Hannah Reding

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

The Python "TypeError: 'int' object does not support item assignment" occurs when we try to assign a value to an integer using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate an integer value.

typeerror int object does not support item assignment

Here is an example of how the error occurs.

main.py
my_int = 123 # ⛔️ TypeError: 'int' object does not support item assignment my_int[0] = 9

We tried to access the integer at index 0 and change the digit which caused the error.

If you mean to declare another integer, simply declare a separate variable with a different name.

main.py
my_int = 123 my_other_int = 9

Primitives like integers, floats and strings are immutable in Python, so chances are you meant to change an int value in a list.

main.py
my_list = [1, 2, 3] my_list[0] = 9 print(my_list) # [9, 2, 3] my_list.append(4) print(my_list) # [9, 2, 3, 4] my_list.insert(0, 10) print(my_list) # [10, 9, 2, 3, 4]

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.

If you have two-dimensional lists, you have to access the list item at the correct index when updating it.

main.py
my_list = [[1], [2], [3]] my_list[0][0] = 9 print(my_list) # 👉️ [[9], [2], [3]]

We accessed the first nested list (index 0) and then updated the value of the first item in the nested list.

Make sure you haven't declared a variable with the same name multiple times and you aren't reassigning a list to an integer somewhere by mistake.

If you need to get a new list by running a computation on each integer value of the original list, use a list comprehension.

main.py
my_list = [1, 2, 3] my_new_list = [x + 10 for x in my_list] print(my_new_list) # 👉️ [11, 12, 13]

The Python "TypeError: 'int' object does not support item assignment" is caused when we try to mutate the value of an int.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_int = 123 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.