IndexError: index 1000 is out of bounds for axis 0 with size 1000

10,981

Solution 1

This line is giving you the error i += 1

If you plan on using the while loop, don't forget to add your break statement, otherwise you'll be stuck in an infinite loop. Without any additional details, I don't see why it is necessary in this case.

In addition to that, I would define H_2 as an empty list, and append any values in your calculation to it. According to the documentation, H_2 needs to be an array-like value.

So it should look like:

import numpy as np
import matplotlib.pyplot as mp

e = np.exp
z = np.arange(1000)
H_2 = []

for i in z:
    H_2.append(0.58*e(-(i/81)**2))

mp.scatter(H_2 , z, c = 'r')
mp.show()

Hopefully the graph appears as expected.

Solution 2

So just as a general primer to indexes you need to remember that indexes are zero based. So if you have an array of 5 elements the index 0 will get you the first element, etc and index 4 will get you the 5th and last element. That being said index 5 is therefore trying to access the 6th element and so is invalid.

Now to Python, you should know that the 'for x in list' statement will iterate through all the elements in the lost, placing the actually value and not the index into the variable x.

Share:
10,981
cat
Author by

cat

Updated on June 05, 2022

Comments

  • cat
    cat almost 2 years

    I am very new to python and indexing is still difficult for me. I am trying to plot few values using iterative operation but it seems it is not working and giving me above error. Please help me. Thanks.

    My code:

    import numpy as np
    import matplotlib.pyplot as mp
    
    e = np.exp
    z = np.arange(1000)
    
    
    for i in z:
        while True:
        H_2 = 0.58*e(-(z[i]/81)**2)
        i += 1
    
    mp.scatter(H_2 , z, c = 'r')
    mp.show()
    
  • Hamms
    Hamms about 8 years
    z[i] in the body of the for loop should probably just be i
  • Hamms
    Hamms about 8 years
    alternatively, H_2 = [0.58*e(-(i/81)**2) for i in z]
  • freshhmints
    freshhmints about 8 years
    You're right about z[i] just being i thanks for pointing that out. I also think using list comprehension would be a better approach as you mentioned, but the OP is new to python so I just left it as is. @Hamms
  • Paul
    Paul almost 8 years
    I don't think any use of a loop is appropriate here. H_2 = 0.58*e(-(z/81)**2) is the proper way to use numpy arrays.
  • cat
    cat almost 8 years
    Thanks @freshhmints, thanks a lot for the useful answer. It has worked perfectly. Sorry for late reply.
  • cat
    cat almost 8 years
    Thanks @karina for useful comment.