Home python How to fix it? 'int' object is not subscriptable

How to fix it? ‘int’ object is not subscriptable

Author

Date

Category

Here’s the task:
Generate 20 random integers ranging from -5 to 4, write them to the array cells. Count how many of them are positive, negative and zero values. Display array elements and counted quantities.
Here is the error text:
a [i] = int (a [i])
TypeError: ‘int’ object is not subscriptable.

How to fix it? Thank you very much!

import random
a = []
for i in range (20):
   a = random.randint (-5,4)
p = []
n = []
z = []
for i in range (20):
   a [i] = int (a [i])
   for i in range (0,20,1):
      if (a [i] & gt; 0):
        p.append (a [i])
      if (a [i] == 0):
        z.append (a [i])
      if (a [i] & lt; 0):
        n.append (a [i])
print ('quantity positive', len (p))
print ('quantity negative', len (n))
print ('quantity zero', len (z))

Answer 1, authority 100%

In the 4th line, you write an integer to the variable “a”:

a = random.randint (-5,4)

Then, on line 9, you try to access the variable “a” by index.

a [i] = int (a [i])

But integer variables cannot be indexed.
To make it work, you need to replace the 4th line with this:

a.append (random.randint (-5,4))

In general, your code is not very pythonic.
Where possible, it is recommended to use include lists instead of loops. They are much more concise and make the code much easier with them than without them.

Your program can be rewritten like this:

import random
a = [random.randint (-5,4) for _ in range (20)]
p = [i for i in a if i & gt; 0]
n = [i for i in a if i & lt; 0]
z = [i for i in a if i == 0]
print ('quantity positive', len (p))
print ('quantity negative', len (n))
print ('quantity zero', len (z))

As you can see, it turned out much clearer than yours.

PS: It is considered a sign of good style to put spaces to the left and right of “equals”, comparison signs and arithmetic symbols. And also a space after the comma.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions