Wed Apr 20 2022·2 min read
Photo by Hannah Reding
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.
Here is an example of how the error occurs.
my_int = 123 # ⛔️ TypeError: 'int' object does not support item assignment my_int = 9
We tried to access the integer at index
0 and change the digit which caused
If you mean to declare another integer, simply declare a separate variable with a different name.
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.
my_list = [1, 2, 3] my_list = 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
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.
my_list = [, , ] my_list = 9 print(my_list) # 👉️ [, , ]
We accessed the first nested list (index
0) and then updated the value of the
first item in the nested list.
If you need to get a new list by running a computation on each integer value of the original list, use a list comprehension.
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
my_int = 123 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True
The type class returns the type of an object.
True if the passed in object is an instance or a subclass of
the passed in class.