The problem is that you are creating a list of mixed types, integers and lists, and then trying to access the integer value as if it was a list.
Let’s use a simple example:
x = 2
y = 3
i = 0
j = 0
array = [x*y]
Now, let’s look at what array
currently contains:
array
>> 6
Now we run your first for loop:
for i in range(x):
array.append([0 for j in range(y)])
And let’s check the new value of array
:
array
>> [6, [0, 0, 0], [0, 0, 0]]
So now we see that the first element of array
is an integer. The remaining elements are all lists with three elements.
The error occurs in the first pass through your nested for loops. In the first pass, i and j are both zero.
array[0][0] = 0*0
>> TypeError: 'int' object does not support item assignment
Since array[0]
is an integer, you can’t use the second [0]
. There is nothing there to get. So, like Ashalynd said, the array = x*y
seems to be the problem.
Depending on what you really want to do, there could be many solutions. Let’s assume you want the first element of your list to be a list of length y, with each value equal to x*y
. Then replace array = [x*y]
with:
array = [x*y for i in range(y)]
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.
Table of contents
- TypeError: ‘int’ object does not support item assignment
- Example
- Solution
- Summary
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:
- How to Solve Python TypeError: ‘str’ object does not support item assignment
- How to Solve Python TypeError: ‘tuple’ object does not support item assignment
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!
Today, we will explore the “typeerror: int object does not support item assignment” error message in Python.
If this error keeps bothering you, don’t worry! We’ve got your back.
In this article, we will explain in detail what this error is all about and why it occurs in your Python script.
Aside from that, we’ll hand you the different solutions that will get rid of this “typeerror: ‘int’ object does not support item assignment” error.
The “typeerror int object does not support item assignment” is an error message in Python that occurs when you try to assign a value to an integer as if it were a list or dictionary, which is not allowed.
It is mainly because integers are immutable in Python, meaning their value cannot be changed after they are created.
In other words, once an integer is created, its value cannot be changed.
For example:
sample = 12345
sample[1] = 5
In this example, the code tries to assign the value 1 to the first element of sample, but sample is an integer, not a list or dictionary, and as a result, it throws an error:
TypeError: 'int' object does not support item assignment
This error message indicates that you need to modify your code to avoid attempting to change an integer’s value using item assignment.
What are the root causes of “typeerror: ‘int’ object does not support item assignment”
Here are the most common root causes of “int object does not support item assignment”, which include the following:
- Attempting to modify an integer directly
- Using an integer where a sequence is expected
- Not converting integer objects to mutable data types before modifying them
- Using an integer as a dictionary key
- Passing an integer to a function that expects a mutable object
- Mixing up variables
- Incorrect syntax
- Using the wrong method or function
How to fix “typeerror: int object does not support item assignment”
Here are the following solutions to fix the “typeerror: ‘int’ object does not support item assignment” error message:
Solution 1: Use a list instead of an integer
Since integers are immutable in Python, we cannot modify them.
Therefore, we can use a mutable data type such as a list instead to modify individual elements within a variable.
sample = [1, 2, 3, 4, 5]
sample[1] = 2
print(sample)
Output:
[1, 2, 3, 4, 5]
Solution 2: Convert the integer to a list first
You have to convert the integer first to a string using the str() function.
Then, convert the string to a list using the list() function.
We can also modify individual elements within the list and join it back into a string using the join() function.
Finally, we convert the string back to an integer using the int() function.
sample = list(str(12345)) sample[1] = '2' sample = int(''.join(sample)) print(sample)
Output:
12345
Solution 3: Use a dictionary instead of an integer
This solution is similar to using a list. We can use a dictionary data type to modify individual elements within a variable.
sample = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
sample['e'] = 10
print(sample)
In this example code, we modify the value of the ‘b’ key within the dictionary.
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 10}
Another example:
my_dict = {1: 'itsourcecode', 2: 'proudpinoy', 3: 'englishtutorhub'}
my_dict[1] = 'code'
print(my_dict[1])
Output:
code
Solution 4: Use a different method or function
You can define sample as a list and append items to the list using the append() method.
For example:
sample = [1, 2, 3, 4, 5] sample.append(6) print(sample)
Output:
[1, 2, 3, 4, 5, 6]
How to avoid “typeerror: int object does not support item assignment”
- You have to use appropriate data types for the task at hand.
- You must convert immutable data types to mutable types before modifying it.
- You have to use the correct operators and functions for specific data types.
- Avoid modifying objects directly if they are not mutable.
Frequently Asked Question (FAQs)
How can I resolve “typeerror: int object does not support item assignment” error message?
You can easily resolve the error by converting the integer object to a mutable data type or creating a new integer object with the desired value.
What causes “int object does not support item assignment” error?
The error occurs when you try to modify an integer object, which is not allowed since integer objects are immutable.
Conclusion
By executing the different solutions that this article has already given, you can definitely resolve the “typeerror: int object does not support item assignment” error message in Python.
We are hoping that this article provides you with sufficient solutions.
You could also check out other “typeerror” articles that may help you in the future if you encounter them.
- Uncaught typeerror: illegal invocation
- Typeerror slice none none none 0 is an invalid key
- Typeerror: cannot read property ‘getrange’ of null
Thank you very much for reading to the end of this article.
Answer by Renata Perez
The most immediate one is that your Temp value is not a sequence that you can assign things to, just an integer (the parentheses don’t do anything). While you could make it into a tuple by adding a comma, that still won’t let you assign values into Temp after it has been created (tuples are immutable). Instead, you probably want a list.,Your Temp is not a tuple, it’s just an integer in parenthesis. You can fix this with a simple ,. Consider the following:,Here’s a minimally changed version of your code that first creates a list of lenp zeros, then replaces their values with the computed ones:,However, there’s another issue with your loop. A for loop like for value in sequence assigns values from the sequence to the variable value. It doesn’t assign indexes! If you need indexes, you can either use enumerate or use a different looping construct, such as a list comprehension.
You are presumably trying to build a list of length lenp
here. You’d need to create a list by multiplication here:
Temp = [None] * lenp
but you’d be better off building the list by appending to it:
Temp = []
for i in p:
Temp.append(T * (i / po) ** rp)
You can collapse the for
loop appending to Temp
into a list comprehension to build the list in one go:
rp=1.331
po=1000
T=280
Temp = [T * (i / po) ** rp for i in range(0, 1200, 10)]
Answer by Erik Ramos
But I get an exception TypeError: ‘int’ object does not support item assignment when I run code above.,TypeError: ‘range’ object is not an iterator in Python,TypeError: the argument of type object after * must be iterative, not int in Python,TypeError: ‘_io.TextIOWrapper’ object is not subscriptable in Python
p=range(0,600,10)
lenp=len(p)
rp=1.331
po=1000
T=280
Temp=(lenp)
for i in p:
Temp[i]=T*(p[i]/po)**rp
print(Temp)
Answer by Bode Davidson
The problem is, when I test it, «self.mouse_c=0, TypeError: ‘int’ object does not support item assignment» comes up. I really don’t know why this is. I assume that the lists are immutable inside the «step» method, but why would this be: why wouldn’t it have full access to its own variables?,
TypeError: object.__new__() takes no parameters
2
,You assign integers in one loop cycle, and get the error in the next, when you try to treat them as lists.,
Delete/Destroy object within wx Floatcanvas
1
Heres how it looks so far:
class Event:
#controlls all actions relating to events including
#mouse events
def __init__(self):
#mouse vars
self.mouse_p = [0,0,0] #previous pressing state of buttons
self.mouse_a = [0,0,0] #whether the buttons are pressed
self.mouse_t = [0,0,0] #time the buttons are pressed
self.mouse_c = [0,0,0] #whether buttons are clicked (in that step)
self.mouse_r = [0,0,0] #whether buttons are released
def step(self):
pygame.event.get()
self.mouse_a = list(pygame.mouse.get_pressed())
print self.mouse_a
for i in range(3):
if (self.mouse_p[i] == 0)and(self.mouse_a[i] == 1):#mouse active
self.mouse_c[i]=1
else:
self.mouse_c[i]=0
if (self.mouse_p[i] == 1)and(self.mouse_a[i] == 0):#mouse released
self.mouse_c = 1
else:
self.mouse_c = 0
if(self.mouse_a[i]==1): #mouse time
self.mouse_t[i] +=1
else:
self.mouse_t[i]=0
self.mouse_p = self.mouse_a
Answer by Aislinn Shaffer
add_attempt=4
LLR_L = signal.copy() * 2 / pow(sigma, 2)
LLR_L_ = LLR_L
indexes = np.argsort(np.abs(LLR_L))[:add_attempt]
comb =[]
for i in indexes:
comb.append(i)
COMB = []
for L in range(0, len(comb) + 1):
for subset in itertools.combinations(comb, L):
COMB.append(subset)
for i_flip in range(len(COMB)):
L[:, n] = LLR_L_
decoding process function here( if fails)
else:
LLR_L_ = LLR_L
for j in range(len(COMB[i_flip])):
if LLR_L[COMB[i_flip][j]] > 0:
LLR_L_[COMB[i_flip][j]] = (-1) * 10
else:
LLR_L_[COMB[i_flip][j]] = 10
Output:indexes [ 3 14 5 22]
comb [3, 14, 5, 22]
COMB [(), (3,), (14,), (5,), (22,), (3, 14), (3, 5), (3, 22), (14, 5), (14, 22), (5, 22), (3, 14, 5), (3, 14, 22), (3, 5, 22), (14, 5, 22), (3, 14, 5, 22)]
Output:Traceback (most recent call last):
File "C:ProgramDataAnaconda3libmultiprocessingpool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "C:Usersankita1268DesktopCRC-BP-Multi-Gmain_Iter_mflip.py", line 120, in func
polar_decoded_llr, a = polar_codes_iter_mflip.FG_decode(signal, polar_iter_num, stage_num, frozen_indexes, info_indexes, B_N, sigma, BIG_NUM, perm[perm_idx], alpha, beta, threshold, H_CRC,T)
File "C:Usersankita1268DesktopCRC-BP-Multi-Gpolar_codes_iter_mflip.py", line 203, in FG_decode
L[:, n] = LLR_L_
TypeError: 'int' object does not support item assignment
"""
[color=#E74C3C] L[:, n] = LLR_L_
TypeError: 'int' object does not support item assignment[/color]
for i_flip in range(add_attempt):
L[:, n] = LLR_L_
decoding process function here( if fails)
else:
LLR_L_ = LLR_L
if LLR_L[indexes[i_flip]] > 0:
LLR_L_[indexes[i_flip]] = (-1) * 10
else:
LLR_L_[indexes[i_flip]] = 10
Answer by Braelynn Phan
I have the this script, in which I need to iterate through the first list that is within the list game_board. Starting at the second element I need to change the values in every other element’s list. However when I run this I am greeted with the error ,The enumerate() function returns a tuple that is (integer, object) — see the python documenation for enumerate.,It would be understandable if IDLE was complaining about me assigning a variable to a str, (which would be an issue with iterating over values rather than indices), but i can’t see why this problem is happening considering I have no integers.,idx is just an integer like 0 and there is no such thing a 0[0]
def create_board():
b = [[['',''] for i in range(8)] for j in range(8)]
return b
game_board = create_board()
for i in game_board[0]:
for idx, val in enumerate(i[1::2]):
idx[0] = 0
idx[1] = 0
print game_board
I have the this script, in which I need to iterate through the first list that is within the list game_board. Starting at the second element I need to change the values in every other element’s list. However when I run this I am greeted with the error
idx[0] = 0
TypeError: 'int' object does not support item assignment
Answer by Louie Dillon
The python variable can store a data type of an another variable. These variables can not be used to assign index value using assignment operator. The variable must be a mutable collection of objects to avoid the error TypeError: ‘type’ object does not support item assignment.,The error TypeError: ‘type’ object does not support item assignment will be shown as below the stack trace. The stack trace will display the line that the assignment operator is attempting to change a value in the variable that contains value as a data type of another variable.,If you create a variable that is assigned to a data type of another variable and attempt to access an index value, this error can be reproduced. In the example below, an attempt is made to change the index value of index 0 in the variable using the assignment operator. That is why the error TypeError: ‘type’ object does not support item assignment will be thrown.,The python error TypeError: ‘type’ object does not support item assignment occurs when an index value is inserted or changed in a variable assigned to a data type. The variable can only be accessed by using an index if it is a mutable collection of objects. If you try to change the index value for the variable assigned to the data type, the error TypeError: ‘type’ object does not support item assignment will be thrown in python.
The error TypeError: ‘type’ object does not support item assignment will be shown as below the stack trace. The stack trace will display the line that the assignment operator is attempting to change a value in the variable that contains value as a data type of another variable.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
x[0] = 10
TypeError: 'type' object does not support item assignment
[Finished in 0.1s with exit code 1]
If you create a variable that is assigned to a data type of another variable and attempt to access an index value, this error can be reproduced. In the example below, an attempt is made to change the index value of index 0 in the variable using the assignment operator. That is why the error TypeError: ‘type’ object does not support item assignment will be thrown.
x = list
x[0] = 10
print x
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
x[0] = 10
TypeError: 'type' object does not support item assignment
[Finished in 0.1s with exit code 1]
If the variable that is assigned to a data type of another variable, there are chances of missing the code for the value assignment. The variable may be expected to store a collection of values, but the data type is assigned due to the coding problem. If the code is changed to assign the value, this error will be fixed.
a=(1,2,3)
x = list(a)
x[0] = 10
print x
Output
[10, 2, 3]
[Finished in 0.1s]
If the variable that is assigned to a data type of another variable, the index value assignment is not possible. Check the assignment of variables and assign them to a mutable collection such as list, set, array, etc. If the variable is assigned to an iterable object, the value can be changed using an index access. This is going to solve the error.
x = [1,2,3]
x[0] = 10
print x
Output
[10, 2, 3]
[Finished in 0.1s]
If you want to store the variable types in a list, create a list of the data types and store the value. Using the index to access the collection of data types.
x = [list] * 5
x[0] = int
print x
Output
[<type 'int'>, <type 'list'>, <type 'list'>, <type 'list'>, <type 'list'>]
[Finished in 0.0s]
If you want to create an empty list, store the value as received, then create an empty list. The value can be added using the command insert in the list.
x = []
x.insert(0,10)
print x
Output
[10]
[Finished in 0.0s]
Aug-13-2019, 12:17 PM
(This post was last modified: Aug-13-2019, 12:35 PM by buran.)
Can someone correct that kind of error?
def new(app): app=0 for i in range(10): app[i]=i+1 print(app)
Posts: 7,958
Threads: 150
Joined: Sep 2016
Reputation:
581
(Aug-13-2019, 12:17 PM)shane1236 Wrote: Can someone correct that kind of error?
In order to fix it, one need to know what expected output is. Currently that One is just you.
epokw
Unladen Swallow
Posts: 3
Threads: 0
Joined: Aug 2019
Reputation:
0
You initialized app as an integer in app=0. Later in the code you called app in app[i], which you can only do with list items and dictionaries, not integers.
I’m not 100% sure what you were trying to do, but if you want to create a list of numbers from 1 to 10, I would suggest initializing app as a list with app = [], and then using the .push() method to add items to the list.
I hope that helps!
Posts: 12
Threads: 4
Joined: Jul 2019
Reputation:
0
Aug-13-2019, 01:09 PM
(This post was last modified: Aug-13-2019, 01:13 PM by shane1236.)
yes I want the same as you said can you just code it for me. Also it runs when I put app=[], however, it doesnot print anything can you look into that??
(Aug-13-2019, 12:33 PM)buran Wrote: I want the same as below post said, however, Also it runs when I put app=[], however, it doesnot print anything can you look into that??
epokw
Unladen Swallow
Posts: 3
Threads: 0
Joined: Aug 2019
Reputation:
0
Aug-13-2019, 01:24 PM
(This post was last modified: Aug-13-2019, 01:24 PM by epokw.)
(Aug-13-2019, 01:09 PM)shane1236 Wrote: yes I want the same as you said can you just code it for me. Also it runs when I put app=[], however, it doesnot print anything can you look into that??
(Aug-13-2019, 12:33 PM)buran Wrote: I want the same as below post said, however, Also it runs when I put app=[], however, it doesnot print anything can you look into that??
Sorry, I made a mistake. You should use the .append() method (not the .push() method, that is from JavaScript ).
Did you forget to call the function?
def new(): app = [] for i in range(10): app.append(i+1) print(app) new()
I wouldn’t have passed «app» in as a parameter to the function, as you did. I suspect you also meant to «print(app)» only once, instead of putting it inside the for loop.
By the way, this might be a bit more advanced, but for future reference, you can cut all those lines down to one by using a list comprehension as such:
app = [i for i in range(1, 11)] print(app)
And that will give you the same output
Posts: 7,958
Threads: 150
Joined: Sep 2016
Reputation:
581