Int object does not support item assignment python ошибка

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”

  1. You have to use appropriate data types for the task at hand.
  2. You must convert immutable data types to mutable types before modifying it.
  3. You have to use the correct operators and functions for specific data types.
  4. 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.

Представим такое: студент только что окончил школу, где изучал Паскаль. В универе на лабораторной по Python ему дали такое задание: заменить в строке все точки на восклицательные знаки.

Студент помнит, что можно обращаться к отдельным элементам строки, поэтому сразу пишет очевидный цикл:

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# делаем цикл, который переберёт все порядковые номера символов в строке
for i in range(len(s)):
    # если текущий символ — точка
    if s[i] == '.':
        # то меняем её на восклицательный знак    
        s[i] = '!'

Но после запуска компьютер выдаёт ошибку:

❌  TypeError: ‘str’ object does not support item assignment

Казалось бы, почему? Есть строка, можно обратиться к отдельным символам, цикл в порядке — что не так-то?

Что это значит: интерпретатор сообщает нам, что не может поменять символ в строке один на другой.

Когда встречается: когда в Python мы пытаемся напрямую заменить символ в строке, как это делали в Паскале или некоторых других языках, которые это умеют. В Python строки хоть и состоят из символов, которые можно прочитать по отдельности, но управлять этими символами он не даёт. 

Что делать с ошибкой TypeError: ‘str’ object does not support item assignment

Решение простое: нужно не работать с символами в строке напрямую, а собирать новую строку из исходной. А всё потому, что Python разрешает прибавлять символы к строке, считая их маленькими строками. Этим и нужно воспользоваться:

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# строка с результатом
r = ''
# делаем цикл, который переберёт все порядковые номера символов в исходной строке
for i in range(len(s)):
    # если текущий символ — точка
    if s[i] == '.':
        # то в новой строке ставим на её место восклицательный знак    
        r = r + '!'
    else:
        # иначе просто переносим символ из старой строки в новую
        r = r + s[i]
# выводим результат
print(r)

Но проще всего, конечно, использовать встроенную функцию replace():

# исходная строка, где нужно заменить точки
s = 'Привет. Это журнал «Код».'
# встроенной функцией меняем точки на восклицательные знаки
s = s.replace('.','!')
# выводим результат
print(s)

Вёрстка:

Кирилл Климентьев

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,955

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 Silenced).

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 Wink

Posts: 7,955

Threads: 150

Joined: Sep 2016

Reputation:
581

Понравилась статья? Поделить с друзьями:
  • Indirection requires pointer operand ошибка
  • Indexerror string index out of range ошибка
  • Indexerror list index out of range ошибка питон
  • Indexerror list index out of range python ошибка
  • Indexerror list assignment index out of range ошибка