Search code examples
pythonlucenesyntax-error

python - IndexError: index 9 is out of bounds for axis 0 with size 1


I'm trying to run the following code. Unfortunately, I get an error that I'm not able to solve myself yet.

import numpy as np
import random

def reallyrandom(arg1, arg2, arg3):
    
    int1=int(arg1)
    int2=int(arg2)
    int3=int(arg3)

    np.random.seed(42)

    x=np.random.randint(0,10, size=int1)
    print(x)
    print(x.shape)
    y=x*int2
    print(y)
    print(y.shape)
    z=y[int3]
    print(z)
    

    print(f"Your random value is {z}")

reallyrandom(1,2,9)

Error:

IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15232/4039400629.py in <module>
     23 
     24 #reallyrandom(59,2,7)
---> 25 reallyrandom(1,2,9)

~\AppData\Local\Temp/ipykernel_15232/4039400629.py in reallyrandom(arg1, arg2, arg3)
     16     print(y)
     17     print(y.shape)
---> 18     z=y[int3]
     19     #print(z)
     20 

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

The problem seems to start in defining value z in line z=y[int3] I have no idea how to solve it. Could someone explain what I'm doing wrong? I found on the internet that it is an index error?

Thank you in advance!


Solution

  • The line z = y[int3] is attempting to get the 9th value from the array y (because the index int3 is 9), but there's only one value in the array. This line:

    x = np.random.randint(0, 10, size=int1)
    

    is creating an array with only one random value in it (because the value of int1 is 1). If you want to create an array of 10 random numbers, for example, use:

    x = np.random.randint(0, 10, size=10)
    

    Alternatively, you can use some other variable for size, but it needs to be larger than the index you pass in z = y[int3] or you'll get the same IndexError.