user3235485
user3235485

Reputation: 13

What does the error "int object has no attribute __getitem__" mean for this code?

I want a loop to create an array of 11 integers y[i] such that y[i] = (i+1)*(i+2) and it gives me an error which I don't understand.

In [100]: y = zeros(11)
     ...: for i in range(11):
     ...:     y[i] = (x[i]+1)*(x[i]+2)
     ...:     
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-7a762b788eff> in <module>()
      1 y = zeros(11)
      2 for i in range(11):
----> 3     y[i] = (x[i]+1)*(x[i]+2)
      4 

TypeError: 'int' object has no attribute '__getitem__' 

Upvotes: 0

Views: 20591

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124318

x is an integer, not an array:

>>> x = i = 0
>>> x[i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__' 

You need to scan back in your code and see what rebound x to an integer.

Your question however implies you think you are executing:

y[i] = (i+1)*(i+2)

but your actual code sample clearly shows you are not. Figure out which code should actually run here first.

Upvotes: 4

embert
embert

Reputation: 7602

Basically that means, that you try to do [] on an int so y or x in your code is an integer

Upvotes: 1

Related Questions