2

I have the following code:

import math
import numpy
import numpy as np
import numpydoc
import matplotlib
x= [1,2 ,3 ,4 ,5 ,6]
y= [5,6,7 ,8 ,9 ,10 ]

ax=np.array(x)
ay=np.array(y)
for i in ax:
    if ax[i]>4:
        print("Hi")
    else:
        print("Hello")

I am getting this error:

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

I want the code to check each value of the array and if the condition in the if statement is satisfied, then the program runs/

0

6 Answers 6

1

Your issue is that you are iterating over the elements of the array, but then trying to use the element as the index. When you get to the last element of ax, you're trying to do ax[6], which is out of range for the size of ax.

You should do one or the other, ie:

for i in ax:
    if i > 4:
        print('Hi')
   else:
        print('Hello')

or

for i in range(len(ax)):
    if ax[i] > 4:
        print("Hi")
    else:
        print("Hello")

Depending on what your actual goal is here, a more pythonic approach could be a list comprehension:

res = ["Hi" if i > 4 else "Hello" for i in ax]
Sign up to request clarification or add additional context in comments.

Comments

1

With this iteration pattern, I would suggest using np.where() as opposed to an explicit for loop:

import numpy as np

ax = np.array([1, 2, 3, 4, 5, 6])
result = np.where(ax > 4, "Hi", "Hello")
print("\n".join(result))

This outputs:

Hello
Hello
Hello
Hello
Hi
Hi

Comments

0

The x Array element is not index so y[x[i]] can out of range.

You can use

for index, value in enumerate(x):
    y[index] # This is correct
    x[value] # This can produce same error :D

1 Comment

The questioner is still here? :D
0

Your iteration is wrong, even for a list. To illustrate:

In [321]: alist = ['ab','cd','ef']
In [322]: for i in alist:
     ...:     print(i)
     ...: 
ab
cd
ef

The iteration variable i is an element of the list, NOT an index.

In [323]: i
Out[323]: 'ef'
In [324]: alist[i]
Traceback (most recent call last):
  Input In [324] in <cell line: 1>
    alist[i]
TypeError: list indices must be integers or slices, not str

It does not make any sense to use it as an index. In your case the problem didn't become obvious until you hit the 6, but ax[i] was wrong even before that.

I've seen this mistake in a number of novice questions, and wonder why? Is it just carelessness, or is there some tutorial that's misleading people?

Comments

0

here you go

print(np.where(ax>4, "Hi", "Hello"))

Comments

0

I ran it as below.

x= [1,2,3,4,5,6]
y= [5,6,7,8,9,10]

ax=np.array(x)
ay=np.array(y)

for i in ax:
    if i>4:
        print("Hi")
    else:
        print("Hello")

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.